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
91 // make sure next character is not an identifier
92 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
93 (c >= '0' && c <= '9') || c === '_' || c === '-' || c === '/' || c === '?' || c === '!') {
96 make('name', str).error("Bad identifier");
102 result.push(make('name', str));
106 // A number cannot start with a decimal point. It must start with a digit,
109 } else if (c >= '0' && c <= '9') {
113 // Look for more digits.
117 if (c < '0' || c > '9') {
124 // Make sure the next character is not a letter.
126 if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '_') {
129 make('number', str).error("Bad number");
132 // Convert the string value to a number. If it is finite, then it is a good
137 result.push(make('number', n));
139 make('number', str).error("Bad number");
144 } else if (c === ';') {
147 if (c === '\n' || c === '\r' || c === '') {
153 // multi-char operator.
155 } else if (prefix.indexOf(c) >= 0) {
160 if (suffix.indexOf(c) < 0) {
166 result.push(make('operator', str));
168 // single-character operator.
172 result.push(make('operator', c));