comparison tpi.js @ 206:b4a9d4e405c5

Implemented a simple interpreter to be used for macro expansion and a driver for testing it
author Mike Pavone <pavone@retrodev.com>
date Wed, 23 Oct 2013 19:10:03 -0700
parents
children 60eff5f81d9a
comparison
equal deleted inserted replaced
205:6fe9343b1400 206:b4a9d4e405c5
1 var module = {exports: {}};
2 var console = {log: function(text){}};
3 var PEG;
4
5 var file = null;
6 var argtype = 'normal';
7 var includes = ['.'];
8 var basedir = '';
9 var debugmode = false;
10 for (var i = 0; i < arguments.length; i++) {
11 switch (argtype) {
12 case 'normal':
13 switch (arguments[i]) {
14 case '-basedir':
15 case '-i':
16 case '-interpdebug':
17 debugmode = true;
18 break;
19 default:
20 if (arguments[i].charAt(0) == '-') {
21 print("unrecognized switch", arguments[i]);
22 quit(1);
23 }
24 file = arguments[i];
25 }
26 break;
27 case '-basedir':
28 if (basedir == '') {
29 basedir = arguments[i];
30 argtype = 'normal';
31 } else {
32 print("only one -basedir option allowed");
33 quit(1);
34 }
35 break;
36 case '-i':
37 includes.push(arguments[i]);
38 argtype = 'normal';
39 break;
40 case '-backend':
41 backend = arguments[i];
42 argtype = 'normal';
43 break;
44 }
45 }
46 if (argtype != 'normal') {
47 print("switch", argtype, "expects a parameter");
48 quit(1);
49 }
50
51 if (!file) {
52 print('usage: d8 tpi.js -- filename');
53 quit(1);
54 }
55 includes.push(basedir + 'modules');
56 interpFile(file, basedir, includes, debugmode);
57
58
59 function parseFile(filename)
60 {
61 debugprint('//parsing', filename);
62 var text = read(filename);
63 try {
64 var parsed = parser.parse(text);
65 } catch (error) {
66 print('SyntaxError on at', error.line, ',', error.column, ':', error.message);
67 var lines = text.split('\n');
68 print(lines[error.line-1]);
69 var spacer = '';
70 for (var i = 1; i < error.column; i++) {
71 if (lines[error.line-1].charAt(i-1) == '\t') {
72 spacer += ' ';
73 } else {
74 spacer += ' ';
75 }
76 }
77 print(spacer + '^');
78 quit(1);
79 }
80 return parsed;
81 }
82
83
84 function interpFile(filename, basedir, includes, debugmode)
85 {
86 load(basedir + 'mquery.js');
87 load(basedir + 'peg.js');
88 PEG = module.exports;
89 load(basedir + 'parser.js');
90 load(basedir + 'interp.js');
91
92 if (debugmode) {
93 debugprint = print;
94 } else {
95 debugprint = function() {};
96 }
97 var parsed = parseFile(filename);
98
99 toplevel = new topenv(includes);
100
101 var mainModule = parsed.eval(toplevel);
102 return mainModule.tpmeth_main();
103 }