aboutsummaryrefslogtreecommitdiff
path: root/treetree.js
blob: c71b12cb3e5b73dfe8d15d64d182fdc6ee07c473 (plain)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
#!/usr/bin/env node

var fs=require("fs"),util=require("util"),kbd=require("kbd");

var flags={"debug":false},TRpreload=undefined;

if(process.argv.length<3){
	console.log("Please supply a treetree source file on the command line.");
	console.log("\t-d  Debug stuff.");
	console.log("\t-s  Preload stack in internal JSON array format in next parameter.");
	process.exit(1);
} else {
	var i,j,skipArg=false;
	for(i=2;i<process.argv.length-1;i++){
		if(skipArg){
			skipArg=false;
			continue;
		}
		if(process.argv[i][0]!="-"){
			console.log("Invalid argument '"+process.argv[i]+"'!");
			process.exit(1);
		}
		for(j=1;j<process.argv[i].length;j++){
			switch(process.argv[i][j]){
			case "d":flags.debug=true;break;
			case "s":TRpreload=JSON.parse(process.argv[i+1]);skipArg=true;break;
			default:
				console.log("Invalid flag '-"+process.argv[i][j]+"'!");
				process.exit(1);
			}
		}
	}
}

function TTerror(msg){
	TTerror.super_.apply(this,arguments);
	this.message=msg.toString();
}
util.inherits(TTerror,Error);

function objcpy(obj){return JSON.parse(JSON.stringify(obj));}

var cmd_list=["INP","OUT","IFI","OFI","IUS","OUS","ICH","OCH","PSH","PLL","SWP","POP","DUP","GRB","REL","INT","FLT","STR","NAN","LEN","SPL","SUM","DIF","PRO","QUO","POW","ROO","LOG","MOD","SIG","PI_","OR_","AND","XOR","INV","NOT","EQU","NEQ","SML","GRT","TAU","E__","RND","JMP","EXJ","IFJ","STP","STK"];

//returns [command term,index after end of command]
function extractCmd(code,startat){
	var i;
	while((code[startat]==" "||code[startat]=="\t"||code[startat]=="\n")&&startat<code.length)startat++;
	if(startat==code.length)return false;
	if(code[startat]=='"'||code[startat]=="'"||code[startat]=="{"){
		var term;
		term="";
		for(i=startat+1;i<code.length;i++){
			if(code[i]==code[startat]||(code[startat]=="{"&&code[i]=="}"))break;
			term+=code[i];
		}
		if(code[startat]=="'"||code[startat]=="{")return extractCmd(code,i+1); //'this is a comment,' {and this too.}
		return [["str",term],i+1];
	} else if(code[startat].match(/[0-9]|-|\./)){
		var neg,dot;
		i=startat;
		neg=code[startat]=="-";
		i+=neg;
		dot=false;
		for(;i<code.length;i++){
			if(code[i]=="."){
				if(!dot)dot=true;
				else break;
			}
			if(!code[i].match(/[0-9]/))break;
		}
		return [[dot?"flt":"int",parseFloat(code.slice(startat,i))],i];
	} else if(code[startat]=="#"){
		var term;
		for(i=startat+1;i<code.length;i++)
			if(code[i]==" "||code[i]=="\t"||code[i]=="\n")break;
		return [["lbl",code.slice(startat+1,i)],i];
	} else if(code[startat]=="@"){
		var term;
		for(i=startat+1;i<code.length;i++)
			if(code[i]==" "||code[i]=="\t"||code[i]=="\n")break;
		return [["ref",code.slice(startat+1,i)],i];
	} else {
		var term;
		if(code.length-startat<3)throw new Error("Invalid command '"+code.slice(startat)+"' at end of code with less than 3 characters!");
		term=code.slice(startat,startat+3).toUpperCase();
		if(cmd_list.indexOf(term)!=-1)return [["cmd",term],startat+3];
		else throw new Error("Unrecognised command '"+term+"'!");
	}
}

var runCmds_state={"in":undefined,"out":undefined,"interm":"\n","outterm":"\n","stdinbuf":""};
//Pass command array and the current tree. The tree is edited in-place.
function runCmds(cmds,TR){
	var cmdidx;
	for(cmdidx=0;cmdidx<cmds.length;cmdidx++){
		if(cmds[cmdidx][0]=="str"||cmds[cmdidx][0]=="int"||cmds[cmdidx][0]=="flt")TR=[cmds[cmdidx][1],TR,false];
		else if(cmds[cmdidx][0]=="ref")TR=[labels[cmds[cmdidx][1]],TR,false]; //yes, a label reference is just the position integer.
		else if(cmds[cmdidx][0]=="cmd"){
			switch(cmds[cmdidx][1]){
			case "INP":
				if(runCmds_state["in"]==undefined){
					var idx,str;
					str=kbd.getLineSync()+"\n";
					idx=str.indexOf(runCmds_state["interm"]);
					while(idx==-1){
						runCmds_state["stdinbuf"]+=str;
						str=kbd.getLineSync()+"\n";
						idx=str.indexOf(runCmds_state["interm"]);
					}
					idx=runCmds_state["stdinbuf"].length+idx;
					runCmds_state["stdinbuf"]+=str;
					TR=[runCmds_state["stdinbuf"].slice(0,idx),TR,false];
					runCmds_state["stdinbuf"]=runCmds_state["stdinbuf"].slice(idx+1,runCmds_state["stdinbuf"].length);
				} else {
					var buf,str,c;
					buf=new Buffer(1);
					str="";
					do{
						fs.readSync(runCmds_state["in"],buf,0,1,null);
						c=String.fromCharCode(buf[0])
						str+=c;
					}while(c!=runCmds_state["interm"]);
					TR=[str.slice(0,-1),TR,false];
				}
				break;
			case "OUT":
				var f,stdout,printPrimaryChildTree;
				if(runCmds_state["out"]==undefined)stdout=true;
				else stdout=false;
				printPrimaryChildTree=function(e){
					while(e!=false){
						if(typeof e[0]!="string")throw new TTerror("Value to be printed, "+e[0].toString()+", is not a string!");
						if(stdout)process.stdout.write(e[0]);
						else fs.writeSync(runCmds_state["out"],new Buffer(e[0]),0,e[0].length,null);
						if(e[2]!==false)printPrimaryChildTree(e[2]);
						e=e[1];
					}
				}
				if(TR===false)throw new TTerror("Tree is empty while processing OUT!");
				if(typeof TR[0]!="string")throw new TTerror("Value to be printed, "+TR[0].toString()+", is not a string!");
				if(stdout)process.stdout.write(TR[0]+runCmds_state["outterm"]);
				else fs.writeSync(runCmds_state["out"],new Buffer(TR[0]+runCmds_state["outterm"]),0,TR[0].length+1,null);
				printPrimaryChildTree(TR[2]);
				TR=TR[1];
				break;
			case "IFI":
				var fname;
				if(typeof TR[0]!="string")throw new TTerror("File name (in IFI) is not a string (namely "+TR[0].toString()+")!");
				if(TR[2]!=false)throw new TTerror("Cannot open multiple files (in IFI), but the root node ('"+TR[0]+"') has secondary children!");
				fname=TR[0];
				TR=[1,TR[1],false]; //"return" 1
				try{
					runCmds_state["in"]=fs.openSync(fname,"r");
				} catch(err){
					TR[0]=0; //"return" 0
				}
				break;
			case "OFI":
				var fname;
				if(typeof TR[0]!="string")throw new TTerror("File name (in OFI) is not a string (namely "+TR[0].toString()+")!");
				if(TR[2]!=false)throw new TTerror("Cannot open multiple files (in OFI), but the root node ('"+TR[0]+"') has secondary children!");
				fname=TR[0];
				TR=[1,TR[1],false]; //"return" 1
				try{
					runCmds_state["out"]=fs.openSync(fname,"w");
				} catch(err){
					TR[0]=0; //"return" 0
				}
				break;
			case "IUS":
				if(runCmds_state["in"]!=undefined){
					fs.closeSync(runCmds_state["in"]);
					runCmds_state["in"]=undefined;
				}
				break;
			case "OUS":
				if(runCmds_state["out"]!=undefined){
					fs.closeSync(runCmds_state["out"]);
					runCmds_state["out"]=undefined;
				}
				break;
			case "ICH":
				if(TR[2]!=false)throw new TTerror("Cannot open multiple files (in ICH), but the root node ('"+TR[0]+"') has secondary children!");
				if(typeof TR[0]!="string")throw new TTerror("String expected (in ICH), got '"+TR[0].toString()+"'!");
				if(TR[0].length!=1)throw new TTerror("String is not one character while processing ICH!");
				runCmds_state["interm"]=TR[0];
				TR=TR[1];
				break;
			case "OCH":
				if(TR[2]!=false)throw new TTerror("Cannot open multiple files (in OCH), but the root node ('"+TR[0]+"') has secondary children!");
				if(typeof TR[0]!="string")throw new TTerror("String expected (in OCH), got '"+TR[0].toString()+"'!");
				if(TR[0].length!=1)throw new TTerror("String is not one character while processing OCH!");
				runCmds_state["outterm"]=TR[0];
				TR=TR[1];
				break;
			case "PSH":case "PLL":
				var n;
				if(TR[2]!=false)throw new TTerror("Cannot operate multiple times (in "+cmds[cmdidx][1]+"), but the root node ('"+TR[0]+"') has secondary children!");
				if(typeof TR[0]!="number"||TR[0]%1!=0)throw new TTerror("Integer expected (in "+cmds[cmdidx][1]+"), got '"+TR[0].toString()+"'!");
				n=TR[0];
				TR=TR[1];
				if(cmds[cmdidx][1]=="PLL")n=-n;
				if(n>0){ //PSH
					var next_part,next_part_parent,moved_node,i;
					next_part_parent=TR;
					for(i=0;i<n;i++){
						next_part_parent=next_part_parent[1];
						if(next_part_parent==false)throw new TTerror("Trying to PSH beyond end of tree (in "+cmds[cmdidx][1]+")!");
					}
					next_part=objcpy(next_part_parent[1]);
					moved_node=[TR[0],next_part,objcpy(TR[2])];
					TR=TR[1];
					next_part_parent[1]=moved_node;
				} else if(n<-1){ //PLL; if n==1 then it pulls the root node onto the root node. Which is useless.
					n=-n;
					var moved_node_parent,i;
					moved_node_parent=TR;
					for(i=0;i<n-1;i++){
						moved_node_parent=moved_node_parent[1];
						if(moved_node_parent==false)throw new TTerror("Trying to PLL beyond end of tree (in "+cmds[cmdidx][1]+")!");
					}
					moved_node=moved_node_parent[1];
					if(moved_node==false)throw new TTerror("Trying to PLL just beyond end of tree (in "+cmds[cmdidx][1]+")!");
					moved_node_parent[1]=objcpy(moved_node[1]);
					moved_node=[moved_node[0],TR,moved_node[2]];
					TR=objcpy(moved_node); //Sorry, garbage colector.
				}
				break;
			case "SWP":
				var temp;
				temp=objcpy(TR[1]);
				TR[1]=objcpy(TR[2]);
				TR[2]=temp;
				break;
			case "POP":
				if(TR==false)throw new TTerror("Cannot POP a non-existant root node!");
				TR=TR[1];
				break;
			case "DUP":
				var newroot;
				newroot=[TR[0],TR,objcpy(TR[2])];
				TR=newroot;
				break;
			case "GRB":
				var inserted_tree,end_tree,rest_tree,i,n;
				if(TR==false)throw new TTerror("Cannot GRB from a non-existant root node!");
				if(TR[2]!=false)throw new TTerror("Cannot operate multiple times (in GRB), but the root node ('"+TR[0]+"') has secondary children!");
				n=TR[0];
				if(typeof n!="number")throw new TTerror("Integer expected (in GRB), got '"+n.toString()+"'!");
				TR=TR[1];
				if(n==0)break;
				inserted_tree=objcpy(TR[1]);
				if(inserted_tree==false)throw new TTerror("No primary child of root node to GRB!");
				end_tree=inserted_tree;
				for(i=0;i<n-1&&end_tree!=false;i++)end_tree=end_tree[1];
				rest_tree=objcpy(end_tree[1]);
				end_tree[1]=false;
				inserted_tree[2]=TR[2];
				TR[2]=inserted_tree;
				TR[1]=rest_tree;
				break;
			case "REL":
				var i,n,inserted_tree,last_inserted,after_inserted,rest_main_tree;
				if(TR==false)throw new TTerror("Cannot REL from a non-existant root node!");
				if(TR[2]!=false)throw new TTerror("Cannot operate multiple times (in REL), but the root node ('"+TR[0]+"') has secondary children!");
				n=TR[0];
				if(typeof n!="number")throw new TTerror("Integer expected (in REL), got '"+n.toString()+"'!");
				if(n==0)break;
				TR=TR[1];
				rest_main_tree=TR[1];
				inserted_tree=TR[2];
				if(inserted_tree==false)throw new TTerror("Not enough secondary children to REL!");
				last_inserted=inserted_tree;
				for(i=0;i<n-1;i++){
					if(last_inserted==false)throw new TTerror("Not enough secondary children to REL!");
					last_inserted=last_inserted[1];
				}
				after_inserted=objcpy(last_inserted[1]);
				last_inserted[1]=rest_main_tree;
				TR[1]=inserted_tree;
				TR[2]=after_inserted;
				break;
			case "INT":break;
			case "FLT":break;
			case "STR":break;
			case "NAN":break;
			case "LEN":break;
			case "SPL":break;
			case "SUM":break;
			case "DIF":break;
			case "PRO":break;
			case "QUO":break;
			case "POW":break;
			case "ROO":break;
			case "LOG":break;
			case "MOD":break;
			case "SIG":break;
			case "PI_":break;
			case "OR_":break;
			case "AND":break;
			case "XOR":break;
			case "INV":break;
			case "NOT":break;
			case "EQU":break;
			case "NEQ":break;
			case "SML":break;
			case "GRT":break;
			case "TAU":break;
			case "E__":break;
			case "RND":break;
			case "JMP":break;
			case "EXJ":break;
			case "IFJ":break;
			case "STP":
				process.exit();
				break;
			case "STK":
				var str;
				str=util.inspect(TR,{"depth":null})+runCmds_state["outterm"];
				if(runCmds_state["out"]==undefined)process.stdout.write(str);
				else fs.writeSync(runCmds_state["out"],new Buffer(str),0,str.length,null);
				break;
			default:
				throw new Error("Internal error: Unrecognised command in internal command array! Please report the command '"+cmds[cmdidx][1]+"'!");
			}
		} else throw new Error("Internal error: Invalid command type! Please report the type '"+cmds[cmdidx][0]+"'!");
		if(flags.debug){
			process.stdout.write("\x1B[36m");
			console.log("%j",TR);
			process.stdout.write("\x1B[0m");
		}
	}
}

//Edits `labels` in-place.
function parseLabels(cmds,labels){
	var i;
	for(i=0;i<cmds.length;i++){
		if(cmds[i][0]=="lbl"){
			labels[cmds[i][1]]=i;
			cmds.splice(i,1);
			i--;
		}
	}
}

/*
`TR` stores the main tree in treetree. `false` indicates non-existance. It
contains a root node with a primary child and a secondary child. Every node is
represented by an array with three items, the first containing the contents of
the node, the second containing the primary child (which is also an array like
this node) and the third containing the second child. An absent child is of
course indicated with the literal value `false`.
For example, the following program:
1 2 3 SWP 4
makes the tree (*'s indicating absence of children, / is a primary child, --
is a secondary child):
    4 *
   /
  3--2 *
 *  /
   1 *
  *
and is represented in `TR` like:
[4,
	[3,
		false,
		[2,
			[1,false,false],
			false
		]
	],
	false
]

Commands, in `cmds`, are each an array with two items, the first being the type
and the second being the value. The types are:
"str", "flt", "int", "lbl", "ref" and "cmd".
"str" contains a literal string, "flt" a literal floating-point and "int" a
literal integer. "lbl" and "ref" contain the names of the labels and "irf"
contains the integer mapping of the label after the first pass. "cmd" indicates
a string with the specific command.

The first pass over the code removes all the "lbl" commands and adds those
labels to `labels`. The second pass interprets the code.
*/

var fname,infile,offset,code,cmds,TR,labels;

fname=process.argv[process.argv.length-1];
try{
	infile=fs.openSync(fname,"r");
	fs.closeSync(infile);
}catch(e){
	console.log("Could not open file '"+fname+"'!");
	process.exit(1);
}
code=fs.readFileSync(fname,{"encoding":"utf8"});
cmds=[]; //command list in array form
offset=0;
while(true){
	offset=extractCmd(code,offset);
	if(offset===false)break;
	cmds.push(offset[0]);
	offset=offset[1];
}

if(TRpreload)TR=TRpreload;
else TR=false; //The Big TRee starts non-existant. Yeah. Well, it is true, sort-of.
labels=[]; //label index
parseLabels(cmds,labels);
if(flags.debug){
	process.stdout.write("\x1B[36m");
	process.stdout.write("Commands: ");
	console.log(cmds);
	process.stdout.write("Labels: ");
	console.log(labels);
	process.stdout.write("\x1B[0m");
}
try{
	runCmds(cmds,TR);
} catch(err) {
	if(err instanceof TTerror){
		console.log("\x1B[31;1mTreetree error:\x1B[0m \x1B[31m"+err.message+"\x1B[0m");
		process.exit(1);
	} else throw err;
}