1 | var Token = require("../lib/Token");
|
2 | var StringSource = require("../lib/StringSource");
|
3 |
|
4 | var Tokeniser = module.exports = function(options) {
|
5 | var keywords = options.keywords;
|
6 | var tokenise = function(input) {
|
7 | var source = new StringSource(input);
|
8 |
|
9 | var createToken = function(startIndex, endIndex) {
|
10 | var value = input.substring(startIndex, endIndex);
|
11 | var tokenType = keywords.indexOf(value) === -1 ? "identifier" : "keyword";
|
12 | return new Token(
|
13 | tokenType,
|
14 | value,
|
15 | source.range(startIndex, endIndex)
|
16 | );
|
17 | };
|
18 |
|
19 | var position = 0;
|
20 | var tokens = [];
|
21 | var done = input === "";
|
22 |
|
23 | while (!done) {
|
24 | var nextWhitespace = indexOfRegex(input, /\s/, position);
|
25 | if (nextWhitespace === -1) {
|
26 | done = true;
|
27 | tokens.push(createToken(position, input.length));
|
28 | } else {
|
29 | tokens.push(createToken(position, nextWhitespace));
|
30 | position = indexOfRegex(input, /\S/, nextWhitespace);
|
31 | }
|
32 | }
|
33 | tokens.push(new Token("end", null, source.range(input.length, input.length)));
|
34 | return tokens;
|
35 | };
|
36 |
|
37 | var indexOfRegex = function(string, regex, startIndex) {
|
38 | startIndex = startIndex || 0;
|
39 | var index = string.substring(startIndex).search(regex);
|
40 | if (index === -1) {
|
41 | return -1;
|
42 | } else {
|
43 | return index + startIndex;
|
44 | }
|
45 | };
|
46 |
|
47 | return {
|
48 | tokenise: tokenise
|
49 | };
|
50 | };
|