3 // (c) 2006 Douglas Crockford
5 // Produce an array of simple token objects from a string.
6 // A simple token object contains these members:
7 // type: 'name', 'string', 'number', 'operator'
8 // value: string or number value of the token
9 // from: index of first character of the token
10 // to: index of the last character + 1
12 // Comments of the ; type are ignored.
14 // Operators are by default single characters. Multicharacter
15 // operators can be made by supplying a string of prefix and
17 // characters. For example,
19 // will match any of these:
20 // <= >> >>> <> >= +: -: &: &&: &&
22 /*jslint onevar: false
25 String.prototype.tokens = function (prefix, suffix) {
26 var c; // The current character.
27 var from; // The index of the start of the token.
28 var i = 0; // The index of the current character.
29 var length = this.length;
30 var n; // The number value.
31 var q; // The quote character.
32 var str; // The string value.
34 var result = []; // An array to hold the results.
36 var make = function (type, value) {
38 // Make a token object.
48 // Begin tokenization. If the source string is empty, return nothing.
54 // If prefix and suffix strings are not provided, supply defaults.
56 if (typeof prefix !== 'string') {
59 if (typeof suffix !== 'string') {
64 // Loop through this text, one character at a time.
78 } else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
83 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
84 (c >= '0' && c <= '9') || c === '_' || c === '-' || c === '/') {
87 } else if (c === '?' || c === '!') {
88 // should only be terminal
92 // make sure next character is not an identifier
93 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
94 (c >= '0' && c <= '9') || c === '_' || c === '-' || c === '/' || c === '?' || c === '!') {
97 make('name', str).error("Bad identifier");
103 result.push(make('name', str));
107 // A number cannot start with a decimal point. It must start with a digit,
110 } else if (c >= '0' && c <= '9') {
114 // Look for more digits.
118 if (c < '0' || c > '9') {
125 // Make sure the next character is not a letter.
127 if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '_') {
130 make('number', str).error("Bad number");
133 // Convert the string value to a number. If it is finite, then it is a good
138 result.push(make('number', n));
140 make('number', str).error("Bad number");
145 } else if (c === ';') {
148 if (c === '\n' || c === '\r' || c === '') {
154 // multi-char operator.
156 } else if (prefix.indexOf(c) >= 0) {
161 if (suffix.indexOf(c) < 0) {
167 result.push(make('operator', str));
169 // single-character operator.
173 result.push(make('operator', c));