forked from GeraldWodni/theforth.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforthParser.js
71 lines (58 loc) · 1.59 KB
/
forthParser.js
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
// minmalistic forth parser for package.fs
// (c)copyright 2015 by Gerald Wodni <[email protected]>
"use strict";
module.exports = function _forthParser( content, words ) {
var remaining = content;
function keyQuery() {
return remaining.length > 0;
}
function keyPeek() {
return remaining.substr(0,1);
}
function key() {
if( !keyQuery() )
return null;
var next = keyPeek();
remaining = remaining.substr(1);
return next;
}
function skip( delimiter ) {
while( keyQuery() && keyPeek() == delimiter )
key();
}
function parse( delimiter ) {
var token = "";
while( true ) {
var c = key();
if( c == delimiter || c == null || c == "\n" || c == "\r" )
if( token == "" && c == null )
return null;
else
return token;
token += c;
}
}
function parseName() {
var word = "";
while( word == "" ) {
skip(" ");
word = parse(" ");
if( word === null )
return null;
}
return word;
}
var context = {
parse: parse,
parseName: parseName
}
while( keyQuery() ) {
var word = parseName();
if( word in words )
words[ word ].apply( context );
else if( word == null )
/* if file ends with multiple newlines do nothing */;
else if( " " in words )
words[ " " ].apply( context, [word] );
}
};