Check-in [c9965b6d9d]
Overview
Comment:now passing all 105 tests
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: c9965b6d9d780fbeb4e06434a4ee742dae0536de
User & Date: suchenwi on 2013-11-19 20:21:26
Other Links: manifest | tags
Context
2013-11-20
20:58
added [catch] check-in: 3d61c6fe53 user: suchenwi tags: trunk
2013-11-19
20:21
now passing all 105 tests check-in: c9965b6d9d user: suchenwi tags: trunk
2013-11-13
22:44
first check-in: 2079bac7f3 user: suchenwi tags: trunk
Changes

Modified tcl053.js from [44d4ee318f] to [7793cfca8e].

1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* =================================================== -*- C++ -*-
 * tcl.js "A Tcl implementation in Javascript"
 *
 * Released under the same terms as Tcl itself.
 * (BSD license found at <http://www.tcl.tk/software/tcltk/license.html>)
 *
 * Based on Picol by Salvatore Sanfilippo (<http://antirez.com/page/picol>)
 * (c) Stéphane Arnold 2007
 * Richard Suchenwirth 2007, 2013: cleanup, additions
 * vim: syntax=javascript autoindent softtabwidth=4
 */

_step = 0; // set to 1 for debugging
var fs = require('fs');
puts = console.log;

function TclInterp () {
    this.patchlevel = "0.5.3";
    this.callframe  = [{}];
    this.level      = 0;
    this.levelcall  = [];
    this.commands   = {};
    this.procs      = [];
    this.script     = "";
    this.OK  = 0;
    this.RET = 1;
    this.BRK = 2;
    this.CNT = 3;
    this.getVar = function(name) {
        var nm = name.toString();
        if (nm.match("^::env[(]")) nm=nm.substr(2);
        if (nm.match("^env[(]")) {
            var key = nm.substr(4,nm.length-5);
            var val = process.env[key];
        } else if (nm.match("^::")) {
            var val = this.callframe[0][nm.substr(2)]; // global
        } else {
            var val = this.callframe[this.level][name];











>
|

|















|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* =================================================== -*- C++ -*-
 * tcl.js "A Tcl implementation in Javascript"
 *
 * Released under the same terms as Tcl itself.
 * (BSD license found at <http://www.tcl.tk/software/tcltk/license.html>)
 *
 * Based on Picol by Salvatore Sanfilippo (<http://antirez.com/page/picol>)
 * (c) Stéphane Arnold 2007
 * Richard Suchenwirth 2007, 2013: cleanup, additions
 * vim: syntax=javascript autoindent softtabwidth=4
 */
// 'use strict'; // breaks some tests, like expr 0376, for loop
var _step = 0; // set to 1 for debugging
var fs = require('fs');
var puts = console.log;

function TclInterp () {
    this.patchlevel = "0.5.3";
    this.callframe  = [{}];
    this.level      = 0;
    this.levelcall  = [];
    this.commands   = {};
    this.procs      = [];
    this.script     = "";
    this.OK  = 0;
    this.RET = 1;
    this.BRK = 2;
    this.CNT = 3;
    this.getVar = function(name) {
        var nm = name.toString();
        if (nm.match("^::env[(]")) nm = nm.substr(2);
        if (nm.match("^env[(]")) {
            var key = nm.substr(4,nm.length-5);
            var val = process.env[key];
        } else if (nm.match("^::")) {
            var val = this.callframe[0][nm.substr(2)]; // global
        } else {
            var val = this.callframe[this.level][name];
48
49
50
51
52
53
54

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    }
    this.setVar("argc",  process.argv.length-2);
    this.setVar("argv0", process.argv[1]);
    this.setVar("argv",  process.argv.slice(2));
    this.setVar("errorInfo", "");

    this.incrLevel = function() {

        this.callframe[++this.level] = {};
        return this.level;
    }
    this.decrLevel = function() {
        this.callframe[this.level] = null;
        this.level--;
        if (this.level<0) throw "Exit application";
        this.result = null;
    }
    this.getCommand = function(name) {
        try {
            return this.commands[name];
        } catch (e) {throw "No such command '"+name+"'";}
    }
    this.registerCommand = function(name, func, privdata) {
        if (func == null) throw "No such function: "+name;
        this.commands[name] = new TclCommand(func, privdata);
    }
    this.registerSubCommand = function(name, subcmd, func, privdata) {
      if (func == null) throw "No such subcommand: "+ name +" " + subcmd;
      var path = name.split(" ");
      var ens;
      name = path.shift();
      var cmd = this.commands[name];
      if (cmd == null) {
	ens = {};
	// ens["subcommands"]  = new TclCommand(Tcl.InfoSubcommands, null);
	this.commands[name] = new TclCommand(Tcl.EnsembleCommand, null, ens);
      }
      ens = this.commands[name].ensemble;
      if (ens == null) throw "Not an ensemble command: '"+name+"'";
      // walks deeply into the subcommands tree
      while (path.length > 0) {
	name = path.shift();
	cmd  = ens[name];
	if (cmd == null) {
	  cmd = new TclCommand(Tcl.EnsembleCommand, null, {});
	  ens[name] = cmd;
	  ens = cmd.ensemble;
	  // ens["subcommands"] = new TclCommand(Tcl.InfoSubcommands, null);
	}
      }
      ens[subcmd] = new TclCommand(func, privdata);
    }
    this.eval = function (code) {
      try {
	return this.eval2(code);







>
|
|


|
|
|
|









|








<












<







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

83
84
85
86
87
88
89
90
91
92
93
94

95
96
97
98
99
100
101
    }
    this.setVar("argc",  process.argv.length-2);
    this.setVar("argv0", process.argv[1]);
    this.setVar("argv",  process.argv.slice(2));
    this.setVar("errorInfo", "");

    this.incrLevel = function() {
      //puts("going down from ("+this.level+"): "+this.levelcall);
      this.callframe[++this.level] = {};
      return this.level;
    }
    this.decrLevel = function() {
      this.callframe[this.level] = null;
      this.level--;
      if (this.level < 0) throw "Exit application";
      this.result = null;
    }
    this.getCommand = function(name) {
        try {
            return this.commands[name];
        } catch (e) {throw "No such command '"+name+"'";}
    }
    this.registerCommand = function(name, func, privdata) {
        if (func == null) throw "No such function: "+name;
        this.commands[name] = new TclCommand(func, privdata);
     }
    this.registerSubCommand = function(name, subcmd, func, privdata) {
      if (func == null) throw "No such subcommand: "+ name +" " + subcmd;
      var path = name.split(" ");
      var ens;
      name = path.shift();
      var cmd = this.commands[name];
      if (cmd == null) {
	ens = {};

	this.commands[name] = new TclCommand(Tcl.EnsembleCommand, null, ens);
      }
      ens = this.commands[name].ensemble;
      if (ens == null) throw "Not an ensemble command: '"+name+"'";
      // walks deeply into the subcommands tree
      while (path.length > 0) {
	name = path.shift();
	cmd  = ens[name];
	if (cmd == null) {
	  cmd = new TclCommand(Tcl.EnsembleCommand, null, {});
	  ens[name] = cmd;
	  ens = cmd.ensemble;

	}
      }
      ens[subcmd] = new TclCommand(func, privdata);
    }
    this.eval = function (code) {
      try {
	return this.eval2(code);
127
128
129
130
131
132
133

134
135
136
137
138
139
140
141
142
143
144



145


146





147
148
149
150
151
152
153
	  text = this.getVar(text);
	} else if (parser.type == (parser.CMD)) {
	  try {
	    text = this.eval2(text);
	  } catch (e) {throw (e + "\nwhile parsing \"" + text + "\"");}
	} else if (parser.type == (parser.ESC)) {
	  // escape handling missing!

	} else if (parser.type == (parser.SEP)) {
	  prevtype = parser.type;
	  continue;
	}
	text = this.objectify(text);
	if (parser.type ==parser.EOL || parser.type == parser.EOF) {
	  prevtype = parser.type;
	  if (args.length > 0) {
	    try {
	      result = this.call(args);
	    } catch(e) {



	      if(e.toString().match("Cannot call method")) 


		throw 'invalid command name "'+args[0].toString()+'"';





	      throw e;
	    }
	    if (this.code != this.OK) return this.objectify(result);
	  }
	  args = [];
	  continue;
	}







>











>
>
>
|
>
>
|
>
>
>
>
>







127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
	  text = this.getVar(text);
	} else if (parser.type == (parser.CMD)) {
	  try {
	    text = this.eval2(text);
	  } catch (e) {throw (e + "\nwhile parsing \"" + text + "\"");}
	} else if (parser.type == (parser.ESC)) {
	  // escape handling missing!
	  // puts("escape handler called");
	} else if (parser.type == (parser.SEP)) {
	  prevtype = parser.type;
	  continue;
	}
	text = this.objectify(text);
	if (parser.type ==parser.EOL || parser.type == parser.EOF) {
	  prevtype = parser.type;
	  if (args.length > 0) {
	    try {
	      result = this.call(args);
	    } catch(e) {
	      if(_step) puts("level: "+this.level+" args: "+args+" exception: "+e);
	      var cmd = this.getCommand(args[0]);
	      if (cmd == null) {
		if(args.length==1 && (args[0].toString().match(/ /))) {
		  throw e;
		}
		throw 'invalid command name "'+args[0]+'"';
	      }
	      if (cmd.ensemble != null) {
		throw 'wrong # args: should be "'+args[0]
		  +' subcommand ?argument ...?"';
	      }
	      throw e;
	    }
	    if (this.code != this.OK) return this.objectify(result);
	  }
	  args = [];
	  continue;
	}
195
196
197
198
199
200
201





202


203
204
205
206










207
208
209
210
211
212
213
214
215
216












217
218
219
220
221
222
223


224
225
226
227
228
229
230
231
232
233
234
235
236
237





















238
239
240
241
242
243
244
      });
    this.registerSubCommand("clock", "scan", function (interp, args) {
        return Date.parse(args[1]);
      });
    this.registerSubCommand("clock", "seconds", function (interp, args) {
	return Math.floor((new Date()).valueOf()/1000);
      });





    


    this.registerSubCommand("dict", "create", function (interp, args) {
	if(args.length % 2 == 0) 
	  throw 'wrong # args: should be "dict create ?key value ...?"';
	return new TclObject(args.slice(1));










      });
    this.registerSubCommand("dict", "get", function (interp, args) {
	if(args.length < 2) 
	  throw 'wrong # args: should be "dict get ?key ...?"';
	var dict = args[1].toList();
	var key  = args[2].toString();
	for (var i=0;i < dict.length;i+=2) {
	  if(dict[i].toString() == key) return dict[i+1];
	}
	throw 'key "'+key+'" not known in dictionary';












      });
    this.registerSubCommand("dict", "set", function (interp, args) {
	this.arity(args, 4);
	var name  = args[1];
	var dict  = interp.getVar(name);
	var key   = args[2].toString();
	var val   = args[3].toString();


	var found = false;
	var list  = dict.toList();
	for (var i=0;i < list.length;i+=2) {
	  if(list[i].toString() == key) {
	    list[i+1] = val;
	    found = true;
	    break;
	  }
	}
	if (!found) {
	  list.push(interp.objectify(key)); 
	  list.push(interp.objectify(val));
	} 
	interp.setVar(name, dict);





















	return dict;
      });
    /*
      if(typeof(jQuery) != 'undefined') {
      this.registerCommand("dom", function (interp, args) {
      var selector = args[1].toString();
      var fn = args[2].toString();







>
>
>
>
>
|
>
>




>
>
>
>
>
>
>
>
>
>



|






>
>
>
>
>
>
>
>
>
>
>
>




<


>
>


|











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
      });
    this.registerSubCommand("clock", "scan", function (interp, args) {
        return Date.parse(args[1]);
      });
    this.registerSubCommand("clock", "seconds", function (interp, args) {
	return Math.floor((new Date()).valueOf()/1000);
      });
    this.registerCommand("concat", function (interp, args) {
        this.arity(args, 1, Infinity);
	var res = [];
	for(var i = 1; i < args.length; i++) {
	  res = res.concat(args[i].toList());
	}
	return res;
      });
    this.registerSubCommand("dict", "create", function (interp, args) {
	if(args.length % 2 == 0) 
	  throw 'wrong # args: should be "dict create ?key value ...?"';
	return new TclObject(args.slice(1));
      });
    this.registerSubCommand("dict", "exists", function (interp, args) {
	if(args.length < 2) 
	  throw 'wrong # args: should be "dict exists dictionary ?key ...?"';
	var dict = args[1].toList();
	var key  = args[2].toString();
	for (var i=0;i < dict.length;i+=2) {
	  if(dict[i].toString() == key) return 1;
	}
	return 0;
      });
    this.registerSubCommand("dict", "get", function (interp, args) {
	if(args.length < 2) 
	  throw 'wrong # args: should be "dict get dictionary ?key ...?"';
	var dict = args[1].toList();
	var key  = args[2].toString();
	for (var i=0;i < dict.length;i+=2) {
	  if(dict[i].toString() == key) return dict[i+1];
	}
	throw 'key "'+key+'" not known in dictionary';
      });
    this.registerSubCommand("dict", "keys", function (interp, args) {
	if(args.length < 2 || args.length > 3) 
	  throw 'wrong # args: should be "dict keys dictionary ?globPattern?"';
	var dict    = args[1].toList();
	var pattern = ".*";
	if(args.length == 3) pattern = "^"+args[2].toString().replace(/\*/g,".*");
	var res  = [];
	for (var i=0;i < dict.length;i+=2) {
	  if(dict[i].toString().match(pattern)) res.push(dict[i]);
	}
	return res;
      });
    this.registerSubCommand("dict", "set", function (interp, args) {
	this.arity(args, 4);
	var name  = args[1];

	var key   = args[2].toString();
	var val   = args[3].toString();
	var dict  = [];
	try {dict = interp.getVar(name);} catch(e) {dict = new TclObject([])};
	var found = false;
	var list  = dict.toList();
	for (var i = 0; i < list.length; i += 2) {
	  if(list[i].toString() == key) {
	    list[i+1] = val;
	    found = true;
	    break;
	  }
	}
	if (!found) {
	  list.push(interp.objectify(key)); 
	  list.push(interp.objectify(val));
	} 
	interp.setVar(name, dict);
	return dict;
      });
    this.registerSubCommand("dict", "unset", function (interp, args) {
	this.arity(args, 3);
	var name  = args[1];
	var key   = args[2].toString();
	var dict  = [];
	try {dict = interp.getVar(name);} catch(e) {dict = new TclObject([])};
	var found = false;
	var list  = dict.toList();
	for (var i = 0; i < list.length; i += 2) {
	  if(list[i].toString() == key) {
	    found = true;
	    break;
	  }
	}
	if(found) {
	  if(i == list.length) i -= 2;
	    list.splice(i, 2);
	    interp.setVar(name, dict);
	}
	return dict;
      });
    /*
      if(typeof(jQuery) != 'undefined') {
      this.registerCommand("dom", function (interp, args) {
      var selector = args[1].toString();
      var fn = args[2].toString();
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298


299

300
301
302
303
304
305
306
307
    */
    this.registerCommand("exit",function (interp, args) {
	this.arity(args, 1,2);
	var rc = 0;
	if (args.length == 2) rc = args[1];
	process.exit(rc);
      });
    acos = Math.acos;
    exp  = Math.exp;
    sqrt = Math.sqrt; // "publish" other Math.* functions as needed

    this.registerCommand("expr", function (interp, args) {
	var expression = args.slice(1).join(" ");
	return interp.expr(interp, expression);
      });
    this.expr = function ($interp, $expression) { // also used in for, if, while
      try {
	var $mx = $expression.match(/(\[.*\])/g);
	for ($i in $mx)
	  puts("have to deal with "+$mx[i].toString());
      } catch(e) {puts(i+". exception: "+e);}
      $mx = $expression.match(/(\$[A-Za-z0-9_:]+)/g);
      for ($i in $mx)


	eval("var "+$mx[$i]+" = "+$interp.getVar($mx[$i].slice(1)));

      var res = eval($expression);
      if(res == false) res = 0; else if(res == true) res = 1;
      return res;
    };
    this.registerSubCommand("file", "dirname", function (interp, args) {
        this.arity(args, 2);
	var path = args[1].toString().split("/");
	path.pop();







|
|
|





|

|
|
|

|
|
>
>
|
>
|







338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    */
    this.registerCommand("exit",function (interp, args) {
	this.arity(args, 1,2);
	var rc = 0;
	if (args.length == 2) rc = args[1];
	process.exit(rc);
      });
    var acos = Math.acos;
    var exp  = Math.exp;
    var sqrt = Math.sqrt; // "publish" other Math.* functions as needed

    this.registerCommand("expr", function (interp, args) {
	var expression = args.slice(1).join(" ");
	return interp.expr(interp, expression);
      });
    this.expr = function (interp, expression) { // also used in for, if, while
      try {
	var mx = expression.match(/(\[.*\])/g);
	for (var i in mx)
	  puts("have to deal with "+mx[i].toString());
      } catch(e) {puts(i+". exception: "+e);}
      mx = expression.match(/(\$[A-Za-z0-9_:]+)/g);
      for (i in mx) {
	var val = interp.getVar(mx[i].slice(1)).toString();
	if(isNaN(val) || !isFinite(val)) val = '"'+val+'"';
	eval("var "+mx[i]+' = '+val);
      }
      var res = eval(expression);
      if(res == false) res = 0; else if(res == true) res = 1;
      return res;
    };
    this.registerSubCommand("file", "dirname", function (interp, args) {
        this.arity(args, 2);
	var path = args[1].toString().split("/");
	path.pop();
333
334
335
336
337
338
339
340

341
342
343
344
345
346
347
348
349
350















351
352







353
354
355
356
357
358
359
360
361
362

363
364
365
366
367
368
369
    this.registerCommand("foreach", function (interp, args) {
        this.arity(args, 4);
        var list = args[2].toList();
        var body = args[3].toString();
        var res    = "";
        interp.inLoop = true;
        interp.code = interp.OK;
        for(i in list) {

             interp.setVar(args[1],interp.objectify(list[i]));
             interp.eval(body);
             if(interp.code == interp.BRK) break;
             if(interp.code == interp.CNT) continue;
        }
        interp.inLoop = false;
        if(interp.code == interp.BRK || interp.code == interp.CNT)
            interp.code=interp.OK;
        return "";
    });















    /*    this.registerCommand("gets", function (interp, args) {
        this.arity(args, 2, 3);







        var reply; // = prompt(args[1],"");
        process.stdin.resume();
        process.stdin.on('data', function(str) {
        reply = str;
            });
        if(args[2] != null) {
            interp.setVar(args[2],interp.objectify(reply));
            return reply.length;
        } else return reply;
        }); */

    this.registerCommand("if", function (interp, args) {
        this.arity(args, 3, Infinity);
        var cond = args[1].toString();
        var test = interp.objectify(interp.expr(interp, cond));
        if (test.toBoolean()) return interp.eval(args[2].toString());
        if (args.length == 3) return;
        for (var i = 3; i < args.length; ) {







|
>
|
|
|
|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

>
>
>
>
>
>
>
|
|
|
|
|

|
|

|
>







398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    this.registerCommand("foreach", function (interp, args) {
        this.arity(args, 4);
        var list = args[2].toList();
        var body = args[3].toString();
        var res    = "";
        interp.inLoop = true;
        interp.code = interp.OK;
        for(var i in list) {
	  //puts("now at "+list[i]+" level: "+interp.level);
	  interp.setVar(args[1],interp.objectify(list[i]));
	  interp.eval(body);
	  if(interp.code == interp.BRK) break;
	  if(interp.code == interp.CNT) continue;
        }
        interp.inLoop = false;
        if(interp.code == interp.BRK || interp.code == interp.CNT)
            interp.code=interp.OK;
        return "";
    });
    this.registerCommand("format", function (interp, args) {
        this.arity(args, 3);
	var fmt = args[1];
	var val = args[2];
	if(fmt=="%x") {
	  var x = new Number(val);
	  return x.toString(16);
	} else if(fmt=="%X") {
	  var x = new Number(val);
	  return x.toString(16).toUpperCase();
	}
	else throw "unknown format";
	
      });
    /*
    this.registerCommand("gets", function (interp, args) {
        this.arity(args, 2, 3);
	this.tmp = null;
	rl.on('line', itp.gets);
	while(true) {
	  if(this.tmp != null) break;
	};
	rl.on('line', this.getsevalputs);
        var reply = this.tmp;
        // = prompt(args[1],"");
        //process.stdin.resume();
        //process.stdin.on('data', function(str) {
        //reply = str;
        //    });
        if(args[2] != null) {
	  interp.setVar(args[2],interp.objectify(reply));
	  return reply.length;
        } else return reply;
      });
    */
    this.registerCommand("if", function (interp, args) {
        this.arity(args, 3, Infinity);
        var cond = args[1].toString();
        var test = interp.objectify(interp.expr(interp, cond));
        if (test.toBoolean()) return interp.eval(args[2].toString());
        if (args.length == 3) return;
        for (var i = 3; i < args.length; ) {
403
404
405
406
407
408
409

410
411
412
413
414
415

416
417
418
419

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439

440





441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

467
468
469
470
471
472
473
        if (!interp.procs[name]) throw '"'+name+'" isn\'t a procedure';
        return interp.getCommand(name).privdata[1];
    });
    this.registerSubCommand("info", "commands", function (interp, args) {
        return interp.mkList(interp.commands);
    });
    this.registerSubCommand("info", "exists", function (interp, args) {

            var name = args[1];
            try {interp.getVar(name); return 1;} catch(e) {return 0;}
    });
    this.registerSubCommand("info", "globals", function (interp, args) {
        return interp.mkList(interp.callframe[0]);
    });

    this.registerSubCommand("info", "isensemble", function (interp, args) {
        this.arity(args, 2);
        var name = args[1].toString();
        return (interp.getCommand(name).ensemble != null);

    });
    this.registerSubCommand("info", "level", function (interp, args) {
	if(args.length == 1)
	  return interp.level;
	var delta = args[1];
	return interp.levelcall[interp.level - delta];
    });
    this.registerSubCommand("info", "na", function (interp, args) {
            return process.execPath;
    });
    this.registerSubCommand("info", "patchlevel", function (interp, args) {
            return interp.patchlevel.toString();
    });
    this.registerSubCommand("info", "procs", function (interp, args) {
        return interp.mkList(interp.procs);
    });
    this.registerSubCommand("info", "script", function (interp, args) {
        return interp.script;
    });
    this.registerSubCommand("info", "vars", function (interp, args) {

        return interp.mkList(interp.callframe[interp.level]);





    });
    this.registerCommand("join", function (interp, args) {
	this.arity(args, 2, 3);
	var lst = args[1].toList();
	var sep = " ";
	if(args.length == 3) sep = args[2].toString();
	var res = [];
	var re  = /^{.*}$/;
	for (i in lst) {
	  var word = lst[i].toString();
	  if (re.test(word)) word = word.substring(1,word.length-1);
	  res.push(word);
	}
	return res.join(sep);
      });
    this.registerCommand("jseval", function (interp, args) {
        return eval(args[1].toString());
      });
    this.registerCommand("lappend", function (interp, args) {
        this.arity(args, 2, Infinity);
        var vname = args[1].toString();
	try {
	  var list = interp.getVar(vname);
	} catch(e) {var list = new TclObject([]);}
        list.toList();
        for (var i = 2; i < args.length; i++) {

	  list.content.push(interp.objectify(args[i]));
        }
        interp.setVar(vname, list);
        return list;
      });
    this.registerCommand("lindex", function (interp, args) {
        this.arity(args, 3, Infinity);







>
|
|




>



|
>
|






|



|








>
|
>
>
>
>
>








|

















>







492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
        if (!interp.procs[name]) throw '"'+name+'" isn\'t a procedure';
        return interp.getCommand(name).privdata[1];
    });
    this.registerSubCommand("info", "commands", function (interp, args) {
        return interp.mkList(interp.commands);
    });
    this.registerSubCommand("info", "exists", function (interp, args) {
        this.arity(args, 2);
	var name = args[1];
	try {interp.getVar(name); return 1;} catch(e) {return 0;}
    });
    this.registerSubCommand("info", "globals", function (interp, args) {
        return interp.mkList(interp.callframe[0]);
    });
    /* not in "real" Tcl
    this.registerSubCommand("info", "isensemble", function (interp, args) {
        this.arity(args, 2);
        var name = args[1].toString();
	var cmd  = interp.getCommand(name);
        return (cmd != null && cmd.ensemble != null)? "1" : "0";
	}); */
    this.registerSubCommand("info", "level", function (interp, args) {
	if(args.length == 1)
	  return interp.level;
	var delta = args[1];
	return interp.levelcall[interp.level - delta];
    });
    this.registerSubCommand("info", "nameofexecutable", function (interp, args) {
            return process.execPath;
    });
    this.registerSubCommand("info", "patchlevel", function (interp, args) {
	return interp.patchlevel;
    });
    this.registerSubCommand("info", "procs", function (interp, args) {
        return interp.mkList(interp.procs);
    });
    this.registerSubCommand("info", "script", function (interp, args) {
        return interp.script;
    });
    this.registerSubCommand("info", "vars", function (interp, args) {
	var res = [];
	for(i in interp.callframe[interp.level]) {
	  try {
	    if(interp.getVar(i) != null) {res.push(i);}
	  } catch(e) {};
	}
	return res;
    });
    this.registerCommand("join", function (interp, args) {
	this.arity(args, 2, 3);
	var lst = args[1].toList();
	var sep = " ";
	if(args.length == 3) sep = args[2].toString();
	var res = [];
	var re  = /^{.*}$/;
	for (var i in lst) {
	  var word = lst[i].toString();
	  if (re.test(word)) word = word.substring(1,word.length-1);
	  res.push(word);
	}
	return res.join(sep);
      });
    this.registerCommand("jseval", function (interp, args) {
        return eval(args[1].toString());
      });
    this.registerCommand("lappend", function (interp, args) {
        this.arity(args, 2, Infinity);
        var vname = args[1].toString();
	try {
	  var list = interp.getVar(vname);
	} catch(e) {var list = new TclObject([]);}
        list.toList();
        for (var i = 2; i < args.length; i++) {
	  if(args[i] == "") args[i] = "{}";
	  list.content.push(interp.objectify(args[i]));
        }
        interp.setVar(vname, list);
        return list;
      });
    this.registerCommand("lindex", function (interp, args) {
        this.arity(args, 3, Infinity);
495
496
497
498
499
500
501




502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
        this.arity(args, 4);
        var list    = interp.objectify(args[1]);
        var start = list.listIndex(args[2]);
        var end     = list.listIndex(args[3])+1;
        try {
	  return list.content.slice(start, end);
        } catch (e) {return [];}




      });
    this.registerCommand("lset", function (interp, args) {
        this.arity(args, 4, Infinity);
        var list = interp.getVar(args[1].toString());
        var elt = list;
        for (var i = 2; i < args.length-2; i++) {
	  elt.toList();
	  elt = interp.objectify(elt.content[elt.listIndex(args[i])]);
        }
        elt.toList();
        i = args.length - 2;
        elt.content[elt.listIndex(args[i])] = interp.objectify(args[i+1]);
        return list;
      });
    this.registerCommand("lsearch", function (interp, args) {
        this.arity(args, 3);
        var lst = args[1].toList();
        for(i in lst) if(lst[i] == args[2].toString()) return i;
        return -1;
      });
    this.registerCommand("lsort", function (interp, args) {
        this.arity(args, 2);
        return args[1].toList().sort();
      });
    this.registerCommand("pid", function (interp, args) {







>
>
>
>

















|







594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        this.arity(args, 4);
        var list    = interp.objectify(args[1]);
        var start = list.listIndex(args[2]);
        var end     = list.listIndex(args[3])+1;
        try {
	  return list.content.slice(start, end);
        } catch (e) {return [];}
      });
    this.registerCommand("lreverse", function (interp, args) {
        this.arity(args, 2);
        return args[1].toList().reverse();
      });
    this.registerCommand("lset", function (interp, args) {
        this.arity(args, 4, Infinity);
        var list = interp.getVar(args[1].toString());
        var elt = list;
        for (var i = 2; i < args.length-2; i++) {
	  elt.toList();
	  elt = interp.objectify(elt.content[elt.listIndex(args[i])]);
        }
        elt.toList();
        i = args.length - 2;
        elt.content[elt.listIndex(args[i])] = interp.objectify(args[i+1]);
        return list;
      });
    this.registerCommand("lsearch", function (interp, args) {
        this.arity(args, 3);
        var lst = args[1].toList();
        for(var i in lst) if(lst[i] == args[2].toString()) return i;
        return -1;
      });
    this.registerCommand("lsort", function (interp, args) {
        this.arity(args, 2);
        return args[1].toList().sort();
      });
    this.registerCommand("pid", function (interp, args) {
592
593
594
595
596
597
598
599
600
601
602
603
604






605
606
607
608
609
610
611
    this.registerCommand("split", function (interp, args) {
        this.arity(args, 2, 3);
        var str = args[1].toString();
        var sep = " ";
        if (args.length == 3) sep = args[2].toString();
	var res = [], e;
        var tmp = str.split(sep);
	for(i in tmp) {
	  e = tmp[i];
	  if(e == "") e = "{}";
	  res.push(e);
	}
	return res.join(" ");






      });
    this.registerSubCommand("string", "equal", function (interp, args) {
        this.arity(args, 3);
        return (args[1].toString() == args[2].toString())? "1": "0";
      });
    this.registerSubCommand("string", "index", function (interp, args) {
        this.arity(args, 3);







|





>
>
>
>
>
>







695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
    this.registerCommand("split", function (interp, args) {
        this.arity(args, 2, 3);
        var str = args[1].toString();
        var sep = " ";
        if (args.length == 3) sep = args[2].toString();
	var res = [], e;
        var tmp = str.split(sep);
	for(var i in tmp) {
	  e = tmp[i];
	  if(e == "") e = "{}";
	  res.push(e);
	}
	return res.join(" ");
      });
    this.registerSubCommand("string", "compare", function (interp, args) {
        this.arity(args, 3);
	var a = args[1].toString();
	var b = args[2].toString();
	return a > b? "1": a < b? "-1": "0";
      });
    this.registerSubCommand("string", "equal", function (interp, args) {
        this.arity(args, 3);
        return (args[1].toString() == args[2].toString())? "1": "0";
      });
    this.registerSubCommand("string", "index", function (interp, args) {
        this.arity(args, 3);
650
651
652
653
654
655
656
657
658
659
660
661

662
663
664
665
666
667
668
669
670
671
672
673

674
675
676
677
678
679
680
        var n    = (args.length == 3)? args[2] : 1;
        var t0   = sec_msec();
        for(var i = 0; i < n; i++) interp.eval(body);
        return (sec_msec()-t0)*1000/n + " microseconds per iteration";
    });
    this.registerCommand("unset", function (interp, args) {
        this.arity(args, 2, Infinity);
        for (var i = 2; i < args.length; i++)
            interp.setVar(args[i], null);
    });
    this.registerCommand("uplevel",function (interp, args) {
        this.arity(args, 3, Infinity);

        var delta = args[1].toInteger();
        interp.level -= delta;
	if(interp.level < 0) {
	  interp.level += delta;
	  throw 'bad level "'+delta+'"';
	}
        for (var i = 2; i < args.length; i++) args[i] = args[i].toString();
        if (args.length == 3) {
	  var code = args[2];
        } else var code = args.slice(2).join(" ");
        var res = interp.eval(code);
        interp.level += delta;

        return res;
      });
    this.registerCommand("while", function (interp, args) {
        this.arity(args, 3);
        var cond = args[1].toString();
        var body = args[2].toString();
        var res  = "";







|
|



>












>







759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
        var n    = (args.length == 3)? args[2] : 1;
        var t0   = sec_msec();
        for(var i = 0; i < n; i++) interp.eval(body);
        return (sec_msec()-t0)*1000/n + " microseconds per iteration";
    });
    this.registerCommand("unset", function (interp, args) {
        this.arity(args, 2, Infinity);
        for (var i = 1; i < args.length; i++)
	  interp.setVar(args[i], null);
    });
    this.registerCommand("uplevel",function (interp, args) {
        this.arity(args, 3, Infinity);
	var mycallframe = interp.callframe[interp.level];
        var delta = args[1].toInteger();
        interp.level -= delta;
	if(interp.level < 0) {
	  interp.level += delta;
	  throw 'bad level "'+delta+'"';
	}
        for (var i = 2; i < args.length; i++) args[i] = args[i].toString();
        if (args.length == 3) {
	  var code = args[2];
        } else var code = args.slice(2).join(" ");
        var res = interp.eval(code);
        interp.level += delta;
	interp.callframe[interp.level] = mycallframe;
        return res;
      });
    this.registerCommand("while", function (interp, args) {
        this.arity(args, 3);
        var cond = args[1].toString();
        var body = args[2].toString();
        var res  = "";
692
693
694
695
696
697
698

699

700
701
702
703
704
705
706
	  interp.code=interp.OK;
        return interp.objectify(res);
      });
    // native cmdname {function(interp, args) {...}}
    this.registerCommand("native", function (interp, args) {
        this.arity(args, 3);
        var cmd = args[1].toList();

        var func = eval(args[2].toString());

        //alert("in: "+args[2].toString()+", func: "+ func);
        if (cmd.length == 1) {
	  interp.registerCommand(cmd[0].toString(), func);
	  return;
        }
        base = cmd[0].toString();
        cmd.shift();







>

>







803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
	  interp.code=interp.OK;
        return interp.objectify(res);
      });
    // native cmdname {function(interp, args) {...}}
    this.registerCommand("native", function (interp, args) {
        this.arity(args, 3);
        var cmd = args[1].toList();
	puts("before eval "+args[2]);
        var func = eval(args[2].toString());
	puts("ok so far");
        //alert("in: "+args[2].toString()+", func: "+ func);
        if (cmd.length == 1) {
	  interp.registerCommand(cmd[0].toString(), func);
	  return;
        }
        base = cmd[0].toString();
        cmd.shift();
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
      case ">":  return a > b? "1":"0";
      case "==": return a == b? "1":"0";
      case "!=": return a != b? "1":"0";
      default:   throw "Unknown operator: '"+name+"'";
      }
    }
    var ops = ["+","-","*","/","%","<",">","==","!="];
    for (i in ops)
      this.registerCommand(ops[i],function (interp, args) {
	  this.arity(args, 3);
	  var name = args[0].toString();
	  var a    = interp.objectify(args[1]);
	  var b    = interp.objectify(args[2]);
	  if (name == '==') 
	    return new TclObject(a.toString() == b.toString()?"1":"0","BOOL");







|







831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
      case ">":  return a > b? "1":"0";
      case "==": return a == b? "1":"0";
      case "!=": return a != b? "1":"0";
      default:   throw "Unknown operator: '"+name+"'";
      }
    }
    var ops = ["+","-","*","/","%","<",">","==","!="];
    for (var i in ops)
      this.registerCommand(ops[i],function (interp, args) {
	  this.arity(args, 3);
	  var name = args[0].toString();
	  var a    = interp.objectify(args[1]);
	  var b    = interp.objectify(args[2]);
	  if (name == '==') 
	    return new TclObject(a.toString() == b.toString()?"1":"0","BOOL");
770
771
772
773
774
775
776
777

778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
	text = [text];
      break;
      }
      return this.objectify(text);
    }
    this.call = function(args) {
      if(_step) puts("this.call "+args);
      var func = this.getCommand(args[0].toString());

      var res  = func.call(this,args);
      switch (this.code) {
      case this.OK: case this.RET: return res;
      case this.BRK:
	if (!this.inLoop) throw "Invoked break outside of a loop";
	break;
      case this.CNT:
	if (!this.inLoop) throw "Invoked continue outside of a loop";
	break;
      default: throw "Unknown return code " + this.code;
      }
      return res;
    }
}








|
>




|


|







883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
	text = [text];
      break;
      }
      return this.objectify(text);
    }
    this.call = function(args) {
      if(_step) puts("this.call "+args);
      var func = this.getCommand(args[0]);
      if(func == null) throw 'invalid command name "'+args[0]+'"';
      var res  = func.call(this,args);
      switch (this.code) {
      case this.OK: case this.RET: return res;
      case this.BRK:
	if (!this.inLoop) throw 'invoked "break" outside of a loop';
	break;
      case this.CNT:
	if (!this.inLoop) throw 'invoked "continue" outside of a loop';
	break;
      default: throw "Unknown return code " + this.code;
      }
      return res;
    }
}

844
845
846
847
848
849
850
851
852
853
854
855
856
857











858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
   } catch (e) {
       interp.decrLevel();
       throw "Tcl.Proc exception "+e;
   }
}
/** Manage subcommands */
Tcl.EnsembleCommand = function (interp, args) {
   var sub    = args[1].toString();
   var main = args.shift().toString()+" "+sub;
   args[0] = main;
   var ens = this.ensemble;
   if (ens == null) {
        throw "Not an ensemble command: "+main;
    } else if( ens[sub] == null) {











     var r = [];
     for (var i in ens) r.push(i);
     r[r.length-1] = "or "+r[r.length-1];
     throw 'unknown or ambiguous subcommand "'+sub+'": must be '+
     r.join(", ");
    }
    return ens[sub].call(interp, args);
}
/** Get subcommands of the current ensemble command. */
/*
Tcl.InfoSubcommands = function(interp, args) {
    var r = [];
    for (var i in this.ensemble) r.push(i);
    return interp.objectify(r);
}
*/
function TclObject(text) {
    this.TEXT    = 0;
    this.LIST    = 1;
    this.INTEGER = 2;
    this.REAL    = 3;
    this.BOOL    = 4;
    switch (arguments[0]) {







|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
<

<
|
<
<
|
<
<
<

<







958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986

987

988


989



990

991
992
993
994
995
996
997
   } catch (e) {
       interp.decrLevel();
       throw "Tcl.Proc exception "+e;
   }
}
/** Manage subcommands */
Tcl.EnsembleCommand = function (interp, args) {
  var sub  = args[1].toString();
  var main = args.shift().toString()+" "+sub;
  args[0]  = main;
  var ens  = this.ensemble;
  if (ens == null) {
    throw "Not an ensemble command: "+main;
  } else if (ens[sub] == null) {
    
    var matches   = 0, lastmatch = "";
    for (var i in ens) { // maybe unambiguous prefix?
      if (i.match("^"+sub) != null) {
	matches  += 1;
	lastmatch = i;
      } 
    }
    if(matches == 1) {
      sub = lastmatch;
    } else {
      var r = [];
      for (i in ens) r.push(i);
      r[r.length-1] = "or "+r[r.length-1];
      throw 'unknown or ambiguous subcommand "'+sub+'": must be '+r.join(", ");

    }

  }


  return ens[sub].call(interp, args);



}

function TclObject(text) {
    this.TEXT    = 0;
    this.LIST    = 1;
    this.INTEGER = 2;
    this.REAL    = 3;
    this.BOOL    = 4;
    switch (arguments[0]) {
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
            if (Tcl.isList.test(res[i]) && !Tcl.isNested.test(res[i]))
                res[i] = "{" + res[i] + "}";
        }
        if (res.length == 1) return res[0];
        return res.join(" ");
    }
    this.toString = function () {
        if (this.type != this.TEXT) {
            if (this.type == this.LIST)
                this.content = this.getString(this.content);
            else this.content = this.content.toString();
            this.type = this.TEXT;
        }
        return this.content;
    }
    this.toList = function () {
        if (this.type != this.LIST) {
            if (this.type != this.TEXT)
                this.content[0] = this.content;
            else {

                var text = this.content;
                if (text.charAt(0) == "{" && text.charAt(text.length-1) == "}")
                    text = text.substring(1, text.length-1);
                if (text == "")
                    return [];

                var parser = new TclParser(text.toString());
                this.content = [];
                for(;;) {
                    parser.parseList();
                    this.content.push(new TclObject(parser.getText()));
                    if (parser.type == parser.EOL || parser.type == parser.ESC)
                        break;
                }
            }

            this.type = this.LIST;
        }
        return this.content;
    }
    this.toInteger = function () {
        if (this.type == this.INTEGER) return this.content;
        this.toString();
        if (this.content.match(Tcl.isHex))
            this.content = parseInt(this.content.substring(2), 16);
        else if (this.content.match(Tcl.isOctal))
            this.content = parseInt(this.content, 8);
        else if (this.content.match(Tcl.isDecimal))
            this.content = parseInt(this.content);
        else throw "Not an integer: '"+this.content+"'";
        if (isNaN(this.content)) throw "Not an integer: '"+this.content+"'";
        this.type = this.INTEGER;
        return this.content;
    }
    this.getFloat = function (text) {
        if (!text.toString().match(Tcl.isReal))
        throw "Not a real: '"+text+"'";
        return parseFloat(text);
    }
    this.toReal = function () {
        if (this.type == this.REAL)
        return this.content;
        this.toString();
        // parseFloat doesn't control all the string, so need to check it
        this.content = this.getFloat(this.content);
        if (isNaN(this.content)) throw "Not a real: '"+this.content+"'";
        this.type = this.REAL;
        return this.content;
    }
    this.getNumber = function () {
        try {
            return this.toInteger();
        } catch (e) {return this.toReal();}
    }
    this.toBoolean = function () {
        if (this.type == this.BOOL) return this.content;
        try {
            this.content = (this.toInteger() != 0);
        } catch (e) {
            var t = this.content;
            if (t instanceof Boolean) return t;
            switch (t.toString().toLowerCase()) {
            case "yes":case "true":case "on":
                this.content = true;
                break;
            case "false":case "off":case "no":
                this.content = false;
                break;
            default:
                throw "Boolean expected, got: '"+this.content+"'";
            }
        }
        this.type = this.BOOL;
        return this.content;
    }
}
function TclCommand(func, privdata) {
  if (func == null) throw "No such function";
  this.func     = func;
  this.privdata = privdata;
  this.ensemble = arguments[2];







|
|
|
|
|
|
|


|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|


|
|
|
|
|
|
|
|
|
|
|
|


|

|


|

|
|
|
|
|
|


|
|
|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054

1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
            if (Tcl.isList.test(res[i]) && !Tcl.isNested.test(res[i]))
                res[i] = "{" + res[i] + "}";
        }
        if (res.length == 1) return res[0];
        return res.join(" ");
    }
    this.toString = function () {
      if (this.type != this.TEXT) {
	if (this.type == this.LIST)
	  this.content = this.getString(this.content);
	else this.content = this.content.toString();
	this.type = this.TEXT;
      }
      return this.content;
    }
    this.toList = function () {
      if (this.type != this.LIST) {
	if (this.type != this.TEXT)
	  this.content[0] = this.content;
	else {

	  var text = this.content;
	  if (text.charAt(0) == "{" && text.charAt(text.length-1) == "}")
	    text = text.substring(1, text.length-1);
	  if (text == "")
	    return [];
	  
	  var parser = new TclParser(text.toString());
	  this.content = [];
	  for(;;) {
	    parser.parseList();
	    this.content.push(new TclObject(parser.getText()));
	    if (parser.type == parser.EOL || parser.type == parser.ESC)
	      break;
	  }
	}	

	this.type = this.LIST;
      }
      return this.content;
    }
    this.toInteger = function () {
      if (this.type == this.INTEGER) return this.content;
      this.toString();
      if (this.content.match(Tcl.isHex))
	this.content = parseInt(this.content.substring(2), 16);
      else if (this.content.match(Tcl.isOctal))
	this.content = parseInt(this.content, 8);
      else if (this.content.match(Tcl.isDecimal))
	this.content = parseInt(this.content);
      else throw "Not an integer: '"+this.content+"'";
      if (isNaN(this.content)) throw "Not an integer: '"+this.content+"'";
      this.type = this.INTEGER;
      return this.content;
    }
    this.getFloat = function (text) {
      if (!text.toString().match(Tcl.isReal))
        throw "Not a real: '"+text+"'";
      return parseFloat(text);
    }
    this.toReal = function () {
      if (this.type == this.REAL)
        return this.content;
      this.toString();
      // parseFloat doesn't control all the string, so need to check it
      this.content = this.getFloat(this.content);
      if (isNaN(this.content)) throw "Not a real: '"+this.content+"'";
      this.type = this.REAL;
      return this.content;
    }
    this.getNumber = function () {
      try {
	return this.toInteger();
      } catch (e) {return this.toReal();}
    }
    this.toBoolean = function () {
      if (this.type == this.BOOL) return this.content;
      try {
	this.content = (this.toInteger() != 0);
      } catch (e) {
	var t = this.content;
	if (t instanceof Boolean) return t;
	switch (t.toString().toLowerCase()) {
	case "yes": case "true": case "on":
	  this.content = true;
	  break;
	case "false": case "off": case "no":
	  this.content = false;
	  break;
	default:
	  throw "Boolean expected, got: '"+this.content+"'";
	}
      }
      this.type = this.BOOL;
      return this.content;
    }
}
function TclCommand(func, privdata) {
  if (func == null) throw "No such function";
  this.func     = func;
  this.privdata = privdata;
  this.ensemble = arguments[2];
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
    while (true) {
      if (this.len == 0) {
	this.end = this.index-1;
	this.type = this.ESC;
	return this.OK;
      }
      if (this.cur == "\\") {
	if (this.len >= 2) this.feedSequence();
      }
      else if ("$[ \t\n\r;".indexOf(this.cur)>=0) {
	if ("$[".indexOf(this.cur)>=0 || !this.insidequote) {
	  this.end = this.index-1;
	  this.type = this.ESC;
	  return this.OK;
	}
      }
      else if (this.cur == '"' && this.insidequote) {
	this.end    = this.index-1;
	this.type = this.ESC;
	this.feedchar();
	this.insidequote = false;
	return this.OK;
      }
      this.feedchar();
    }
    return this.OK;
  }
  this.parseList = function () {
    level = 0;
    this.start = this.index;
    while (true) {
      if (this.len == 0) {
	this.end = this.index;
	this.type = this.EOL;
	return;
      }
      switch (this.cur) {
      case "\\":
	if (this.len >= 2) this.feedSequence();
	break;
      case " ": case "\t": case "\n": case "\r":
	if (level > 0) break;
	this.end    = this.index - 1;
	this.type = this.SEP;
	this.feedchar();
	return;
      case '{': level++; break;
      case '}': level--; break;
      }
      this.feedchar();







|




















|



|









|







1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
    while (true) {
      if (this.len == 0) {
	this.end = this.index-1;
	this.type = this.ESC;
	return this.OK;
      }
      if (this.cur == "\\") {
	//if (this.len >= 2) this.feedSequence();
      }
      else if ("$[ \t\n\r;".indexOf(this.cur)>=0) {
	if ("$[".indexOf(this.cur)>=0 || !this.insidequote) {
	  this.end = this.index-1;
	  this.type = this.ESC;
	  return this.OK;
	}
      }
      else if (this.cur == '"' && this.insidequote) {
	this.end    = this.index-1;
	this.type = this.ESC;
	this.feedchar();
	this.insidequote = false;
	return this.OK;
      }
      this.feedchar();
    }
    return this.OK;
  }
  this.parseList = function () {
    var level = 0;
    this.start = this.index;
    while (true) {
      if (this.len == 0) {
	this.end  = this.index;
	this.type = this.EOL;
	return;
      }
      switch (this.cur) {
      case "\\":
	if (this.len >= 2) this.feedSequence();
	break;
      case " ": case "\t": case "\n": case "\r":
	if (level > 0) break;
	this.end  = this.index - 1;
	this.type = this.SEP;
	this.feedchar();
	return;
      case '{': level++; break;
      case '}': level--; break;
      }
      this.feedchar();
1211
1212
1213
1214
1215
1216
1217

1218
1219

1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236

1237
1238
1239

1240
1241
1242
1243
1244
1245
1246
	continue;
      }
      return this.parseString();
    }
    return this.OK; // unreached
  }
  this.feedSequence = function () {

    if (this.cur != "\\") throw "Invalid escape sequence";
    var cur = this.steal(1);

    var specials = {};
    specials.a = "\a";
    specials.b = "\b";
    specials.f = "\f";
    specials.n = "\n";
    specials.r = "\r";
    specials.t = "\t";
    specials.v = "\v";
    switch (cur) {
    case 'u':
      var hex = this.steal(4);
      if (hex != Tcl.isHexSeq.exec(hex))
	throw "Invalid unicode escape sequence: "+hex;
      cur = String.fromCharCode(parseInt(hex,16));
      break;
    case 'x':
      var hex = this.steal(2);

      if (hex != Tcl.isHexSeq.exec(hex))
	throw "Invalid unicode escape sequence: "+hex;
      cur = String.fromCharCode(parseInt(hex,16));

      break;
    case "a": case "b": case "f": case "n":
    case "r": case "t": case "v":
      cur = specials[cur];
      break;
    default:
      if ("0123456789".indexOf(cur) >= 0) {







>


>

















>



>







1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
	continue;
      }
      return this.parseString();
    }
    return this.OK; // unreached
  }
  this.feedSequence = function () {
    //return;
    if (this.cur != "\\") throw "Invalid escape sequence";
    var cur = this.steal(1);
    //puts("enter feedSequence, text: "+this.text+" cur: "+cur);
    var specials = {};
    specials.a = "\a";
    specials.b = "\b";
    specials.f = "\f";
    specials.n = "\n";
    specials.r = "\r";
    specials.t = "\t";
    specials.v = "\v";
    switch (cur) {
    case 'u':
      var hex = this.steal(4);
      if (hex != Tcl.isHexSeq.exec(hex))
	throw "Invalid unicode escape sequence: "+hex;
      cur = String.fromCharCode(parseInt(hex,16));
      break;
    case 'x':
      var hex = this.steal(2);
      puts("enter case x, hex: '"+hex+"'");
      if (hex != Tcl.isHexSeq.exec(hex))
	throw "Invalid unicode escape sequence: "+hex;
      cur = String.fromCharCode(parseInt(hex,16));
      //puts("hex: "+hex.toString()+" cur: "+cur);
      break;
    case "a": case "b": case "f": case "n":
    case "r": case "t": case "v":
      cur = specials[cur];
      break;
    default:
      if ("0123456789".indexOf(cur) >= 0) {
1254
1255
1256
1257
1258
1259
1260

1261
1262
1263
1264
1265
1266
1267
    this.text[index] = cur;
    this.feedchar();
  }
  this.steal = function (n) {
    var tail = this.text.substring(this.index+1);
    var word = tail.substr(0, n);
    this.text = this.text.substring(0, this.index-1) + tail.substring(n);

    return word;
  }
  this.feedcharstart = function () {
    this.feedchar();
    this.start = this.index;
  }
  this.setPos = function (index) {







>







1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
    this.text[index] = cur;
    this.feedchar();
  }
  this.steal = function (n) {
    var tail = this.text.substring(this.index+1);
    var word = tail.substr(0, n);
    this.text = this.text.substring(0, this.index-1) + tail.substring(n);
    //puts("tail: "+tail+" word: "+word);
    return word;
  }
  this.feedcharstart = function () {
    this.feedchar();
    this.start = this.index;
  }
  this.setPos = function (index) {
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297






1298
1299
1300
process.argv.slice(2).forEach(function(cmd,index,array) {
       itp.eval(cmd);
     });
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('% ');
rl.prompt();
rl.on('line', function(line) {
    try {
      res = itp.eval(line.trim());
    } catch(e) {res = e;}
    if(res != null && res.toString() != "" && res.toString().length) 
      console.log(res.toString());
    rl.prompt();






  }).on('close',function() {
    process.exit(0);
  });







|




|

>
>
>
>
>
>
|


1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
process.argv.slice(2).forEach(function(cmd,index,array) {
       itp.eval(cmd);
     });
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('% ');
rl.prompt();
itp.getsevalputs = function(line) {
    try {
      res = itp.eval(line.trim());
    } catch(e) {res = e;}
    if(res != null && res.toString() != "" && res.toString().length) 
      puts(res.toString());
    rl.prompt();
};
itp.gets = function(line) {
  puts("received "+line); 
  this.tmp = line;
}
rl.on('line', itp.getsevalputs
).on('close',function() {
    process.exit(0);
  });

Modified test_tcljs.tcl from [9b4e7f495f] to [c15ca09a61].

1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37







38


39

40
41




42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59


60

61

62


63
64
65
66







67
68
69




70
71
72
73
74
75
76
77
78
79
80
81



82


83
84
85
86

87






88
89





90
91
92
93
94
95
96
97
98


99



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120


121
122

123
124
125
126

127

128

# test suite for TclJS
# This file is designed so it can also run in a tclsh. Some JavaScript goodies,
# like 1/0, sqrt(-1) were excluded from the tests.
# [clock format 0] was excluded because the timezone string differed.


set version 0.5.3
set total  0
set passed 0
set fail   0
puts "------------------------ [info script]"

proc e.g. {cmd -> expected} {
    incr ::total
    incr ::fail ;# to also count exceptions
    set mres [uplevel 1 $cmd]
    if [!= $mres $expected] {

	puts "**** $cmd -> $mres, expected $expected"
    } else {incr ::passed; incr ::fail -1}
}
#------------------------------- commands not in real Tcl
if [info exists auto_path] {
    proc func {name argl body} {proc $name $argl [list expr $body]}
    func +   {a b} {$a +  $b}
    func !=  {a b} {$a != $b}
    func *   {a b} {$a *  $b}
    func ==  {a b} {$a == $b}
    func <   {a b} {$a <  $b}
    set noTcl 0
} else {set noTcl 1}


# e.g. {exec echo hello} -> hello

e.g. {append new hello} -> hello
e.g. {set x foo}        -> foo
e.g. {append x bar}     -> foobar








e.g. {set d [dict create a 1 b 2 c 3]} -> {a 1 b 2 c 3}


e.g. {dict get $d b} -> 2

e.g. {dict set d b 5} -> {a 1 b 5 c 3}
e.g. {dict set d x 7} -> {a 1 b 5 c 3 x 7}





e.g. {set home [file dirname [pwd]]; list} -> {}
e.g. {string equal [set env(HOME)] $home}   -> 1
e.g. {string equal [set ::env(HOME)] $home} -> 1

e.g. {expr 6*7}         -> 42
e.g. {expr {6 * 7 + 1}} -> 43
e.g. {set x 43}         -> 43
e.g. {expr {$x-1}}      -> 42
e.g. {expr $x-1}        -> 42
if $noTcl {
    e.g. {clock format 0} -> {Thu Jan 01 1970 01:00:00 GMT+0100 (CET)}
    e.g. {set i [expr 1/0]} -> Infinity
    e.g. {expr $i==$i+42}   -> 1
    e.g. {set n [expr sqrt(-1)]} -> NaN
    e.g. {expr $n == $n} -> 0
    e.g. {expr $n==$n}   -> 0
    e.g. {expr $n!=$n}   -> 1


}

e.g. {expr 0xFF}   -> 255

e.g. {expr 0376}   -> 254


e.g. {expr 6 * 7}  -> 42

e.g. {expr 1 == 2} -> 0
e.g. {expr 1 < 2}  -> 1








set forres ""
e.g. {for {set i 0} {$i < 5} {incr i} {append forres $i}; set forres} -> 01234





e.g. {set x 41}  -> 41
e.g. {incr x}    -> 42
e.g. {incr x 2}  -> 44
e.g. {incr x -3} -> 41

e.g. {info args e.g.} -> {cmd -> expected}
e.g. {unset -nocomplain foo} -> {}
e.g. {info exists foo} -> 0
e.g. {set foo 42}      -> 42
e.g. {info exists foo} -> 1
e.g. {info level}      -> 0 ;# e.g. runs the command one level up



e.g. {info patchlevel} -> $version



e.g. {join {a b c}}     -> {a b c}
e.g. {join {a b c} +}   -> {a+b+c}
e.g. {join {a {b c} d}} -> {a b c d}








e.g. {expr !0}  -> 1
e.g. {expr !42} -> 0






e.g. {regexp {X[ABC]Y} XAY}    -> 1
e.g. {regexp {X[ABC]Y} XDY}    -> 0
e.g. {regsub {[A-C]+} uBAAD x} -> uxD 

e.g. {split "a b  c d"}     -> {a b {} c d}
e.g. {split " a b  c d"}     -> {{} a b {} c d}
e.g. {split "a b  c d "}     -> {a b {} c d {}}
e.g. {split usr/local/bin /} -> {usr local bin}






e.g. {string equal foo foo}   -> 1
e.g. {string equal foo bar}   -> 0
e.g. {string index abcde 2}   -> c
e.g. {string length ""}       -> 0
e.g. {string length foo}      -> 3
e.g. {string range hello 1 3} -> ell
e.g. {string tolower TCL}     -> tcl
e.g. {string toupper tcl}     -> TCL
e.g. {string trim " foo "}    -> foo

e.g. {set x {a b c}} -> {a b c}
e.g. {lappend x d}   -> {a b c d}
e.g. {set x}         -> {a b c d}
e.g. {lset x 3 e}    -> {a b c e}
e.g. {llength $x}    -> 4
e.g. {lindex $x 2}   -> c
e.g. {lrange $x 1 2} -> {b c}
e.g. {lsearch $x b}  -> 1
e.g. {lsearch $x y}  -> -1
e.g. {lsort {z x y}} -> {x y z}



e.g. {proc f x {set y 0; info vars}} -> ""
e.g. {f 41} -> {x y} ;# must fix proc call in uplevel issue

set tmp [f 41]; e.g. {set tmp} -> {x y}
e.g. {info args f} -> x
e.g. {info body f} -> {set y 0; info vars}
#e.g. {f 42} -> {x y} ;# must fix proc call in uplevel issue



puts "total $total tests, passed $passed, failed $fail"






>

|
|
|
|




|
|
>
|


<
<
<
<
<
<
<
<
<
<

<
|





>
>
>
>
>
>
>

>
>
|
>
|
|
>
>
>
>










|







>
>
|
>
|
>
|
>
>

<


>
>
>
>
>
>
>



>
>
>
>












>
>
>
|
>
>




>

>
>
>
>
>
>
|
|
>
>
>
>
>









>
>

>
>
>






|
|


|
<
<
<
<
<
<
<
<
<

>
>
|
<
>
|
<
<
<
>
|
>
|
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21










22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153









154
155
156
157

158
159



160
161
162
163
164
# test suite for TclJS
# This file is designed so it can also run in a tclsh. Some JavaScript goodies,
# like 1/0, sqrt(-1) were excluded from the tests.
# [clock format 0] was excluded because the timezone string differed.

set vars [info vars] ;# for later cleanup
set version 0.5.3
set total   0
set passed  0
set fail    0
puts "------------------------ [info script] patchlevel: [info patchlevel]"

proc e.g. {cmd -> expected} {
    incr ::total
    incr ::fail ;# to also count exceptions
    set res [uplevel 1 $cmd]
    if ![string equal $res $expected] {
    #if {$res != $expected} {} #should work, but wouldn't
	puts "**** $cmd -> $res, expected: $expected"
    } else {incr ::passed; incr ::fail -1}
}












# e.g. {exec echo hello} -> hello ;# needs blocking exec

e.g. {append new hello} -> hello
e.g. {set x foo}        -> foo
e.g. {append x bar}     -> foobar

proc sum args {expr [join $args +]}
e.g. {sum 1 2 3} -> 6
#native sum2 {function (interp, args) {return eval(args.join("+"));}}
#e.g. {sum2 2 3 4} -> 9

e.g. {concat {a b} {c d}} -> {a b c d}

e.g. {set d [dict create a 1 b 2 c 3]} -> {a 1 b 2 c 3}
e.g. {dict exists $d c} -> 1
e.g. {dict exists $d x} -> 0
e.g. {dict get $d b}    -> 2
e.g. {dict keys $d}     -> {a b c}
e.g. {dict set d b 5}   -> {a 1 b 5 c 3}
e.g. {dict set d x 7}   -> {a 1 b 5 c 3 x 7}
e.g. {dict unset d b}   -> {a 1 c 3 x 7}
e.g. {dict unset d x}   -> {a 1 c 3}
e.g. {dict unset d nix} -> {a 1 c 3}
e.g. {dict set dx a 1}  -> {a 1} ;# create new dict if not exists

e.g. {set home [file dirname [pwd]]; list} -> {}
e.g. {string equal [set env(HOME)] $home}   -> 1
e.g. {string equal [set ::env(HOME)] $home} -> 1

e.g. {expr 6*7}         -> 42
e.g. {expr {6 * 7 + 1}} -> 43
e.g. {set x 43}         -> 43
e.g. {expr {$x-1}}      -> 42
e.g. {expr $x-1}        -> 42
if ![info exists auto_path] { ;#these tests are not for a real tclsh
    e.g. {clock format 0} -> {Thu Jan 01 1970 01:00:00 GMT+0100 (CET)}
    e.g. {set i [expr 1/0]} -> Infinity
    e.g. {expr $i==$i+42}   -> 1
    e.g. {set n [expr sqrt(-1)]} -> NaN
    e.g. {expr $n == $n} -> 0
    e.g. {expr $n==$n}   -> 0
    e.g. {expr $n!=$n}   -> 1
    e.g. {info patchlevel} -> $version
    e.g. {set vars}      -> {argc argv0 argv errorInfo} ;# many more in real Tcl

}
e.g. {expr 0xFF}               -> 255
e.g. {set x 0xFF; expr {$x+0}} -> 255
e.g. {expr 0376}               -> 254
e.g. {set x 0375; expr $x}     -> 253
e.g. {expr {$x}}   -> 253
e.g. {expr 6 * 7}  -> 42

e.g. {expr 1 == 2} -> 0
e.g. {expr 1 < 2}  -> 1
e.g. {expr !0}     -> 1
e.g. {expr !42}    -> 0
e.g. {set x 3}     -> 3
e.g. {expr $x+1}   -> 4
e.g. {expr {$x+1}} -> 4
e.g. {set x a; set y b; expr {$x == $y}} -> 0
e.g. {expr {$x != $y}} -> 1

set forres ""
e.g. {for {set i 0} {$i < 5} {incr i} {append forres $i}; set forres} -> 01234
e.g. {foreach i {a b c d e} {append foreachres $i}; set foreachres}   -> abcde

e.g. {format %x 255} -> ff
e.g. {format %X 254} -> FE

e.g. {set x 41}  -> 41
e.g. {incr x}    -> 42
e.g. {incr x 2}  -> 44
e.g. {incr x -3} -> 41

e.g. {info args e.g.} -> {cmd -> expected}
e.g. {unset -nocomplain foo} -> {}
e.g. {info exists foo} -> 0
e.g. {set foo 42}      -> 42
e.g. {info exists foo} -> 1
e.g. {info level}      -> 0 ;# e.g. runs the command one level up
e.g. {proc f x {set y 0; info vars}} -> ""
e.g. {f 41}            -> {x y}
set tmp [f 40]; e.g. {lappend tmp z} -> {x y z}
e.g. {info args f}      -> x
e.g. {info body f}      -> {set y 0; info vars}
e.g. {info bod f}       -> {set y 0; info vars}

e.g. {join {a b c}}     -> {a b c}
e.g. {join {a b c} +}   -> {a+b+c}
e.g. {join {a {b c} d}} -> {a b c d}
e.g. {join {a b c} ""}  -> abc

e.g. {set x {a b c}}      -> {a b c}
e.g. {set x [list a b c]} -> {a b c}
e.g. {lappend x}          -> {a b c}
e.g. {lappend x {}}       -> {a b c {}}
e.g. {set x}              -> {a b c {}}
e.g. {lset x 3 e}         -> {a b c e}
e.g. {llength $x}         -> 4
e.g. {lindex $x 2}        -> c
e.g. {lrange $x 1 2}      -> {b c}
e.g. {lreverse {a b c}}   -> {c b a}
e.g. {lsearch $x b}       -> 1
e.g. {lsearch $x y}       -> -1
e.g. {lsort {z x y}}      -> {x y z}

e.g. {regexp {X[ABC]Y} XAY}    -> 1
e.g. {regexp {X[ABC]Y} XDY}    -> 0
e.g. {regsub {[A-C]+} uBAAD x} -> uxD 

e.g. {split "a b  c d"}     -> {a b {} c d}
e.g. {split " a b  c d"}     -> {{} a b {} c d}
e.g. {split "a b  c d "}     -> {a b {} c d {}}
e.g. {split usr/local/bin /} -> {usr local bin}
e.g. {split /usr/local/bin /} -> {{} usr local bin}
e.g. {split abc ""}          -> {a b c}

e.g. {string compare a b}     -> -1
e.g. {string compare b a}     -> 1
e.g. {string compare b b}     -> 0
e.g. {string equal foo foo}   -> 1
e.g. {string equal foo bar}   -> 0
e.g. {string index abcde 2}   -> c
e.g. {string length ""}       -> 0
e.g. {string length foo}      -> 3
e.g. {string range hello 1 3} -> ell
e.g. {string tolower Tcl}     -> tcl
e.g. {string toupper Tcl}     -> TCL
e.g. {string trim " foo "}    -> foo

#e.g. {set x a.\x62.c} -> a.b.c ;# severe malfunction, breaks test suite operation :(










puts "total $total tests, passed $passed, failed $fail"
#----------- clean up variables used in tests
foreach var [info vars] {

    set pos [lsearch $vars $var] ;# expr can't substitute commands yet
    set neq [string compare $var vars]



    if {$var != "vars" && $pos < 0} {unset $var}
}
unset vars var pos neq
puts "vars now: [info vars]"
puts "[llength [info commands]] commands implemented"