JSDOC/TokenReader.js
[gnome.introspection-doc-generator] / JSDOC / TokenReader.js
1 //<script type="text/javascript">
2
3  
4 XObject = imports.XObject.XObject;
5 console = imports.console.console;
6
7
8 Token   = imports.Token.Token;
9 Lang    = imports.Lang.Lang;
10
11 /**
12         @class Search a {@link JSDOC.TextStream} for language tokens.
13 */
14 TokenReader = XObject.define(
15     function(o) {
16         
17         XObject.extend(this, o || {});
18         
19     },
20     Object,
21     {
22         /** @cfg {Boolean} collapseWhite merge multiple whitespace/comments into a single token **/
23         collapseWhite : false, // only reduces white space...
24         /** @cfg {Boolean} keepDocs keep JSDOC comments **/
25         keepDocs : true,
26         /** @cfg {Boolean} keepWhite keep White space **/
27         keepWhite : false,
28         /** @cfg {Boolean} keepComments  keep all comments **/
29         keepComments : false,
30         /** @cfg {Boolean} sepIdents seperate identifiers (eg. a.b.c into ['a', '.', 'b', '.', 'c'] ) **/
31         sepIdents : false,
32         /** @cfg {String} filename name of file being parsed. **/
33         filename : '',
34         
35         /**
36          * tokenize a stream
37          * @return {Array} of tokens
38          * 
39          * ts = new TextStream(File.read(str));
40          * tr = TokenReader({ keepComments : true, keepWhite : true });
41          * tr.tokenize(ts)
42          * 
43          */
44             
45
46
47         tokenize : function(/**JSDOC.TextStream*/stream) {
48             this.line =1;
49             var tokens = [];
50             /**@ignore*/ 
51             tokens.last    = function() { return tokens[tokens.length-1]; }
52             /**@ignore*/ 
53             tokens.lastSym = function() {
54                 for (var i = tokens.length-1; i >= 0; i--) {
55                     if (!(tokens[i].is("WHIT") || tokens[i].is("COMM"))) return tokens[i];
56                 }
57             }
58
59             while (!stream.look().eof) {
60                 if (this.read_mlcomment(stream, tokens)) continue;
61                 if (this.read_slcomment(stream, tokens)) continue;
62                 if (this.read_dbquote(stream, tokens))   continue;
63                 if (this.read_snquote(stream, tokens))   continue;
64                 if (this.read_regx(stream, tokens))      continue;
65                 if (this.read_numb(stream, tokens))      continue;
66                 if (this.read_punc(stream, tokens))      continue;
67                 if (this.read_newline(stream, tokens))   continue;
68                 if (this.read_space(stream, tokens))     continue;
69                 if (this.read_word(stream, tokens))      continue;
70                 
71                 // if execution reaches here then an error has happened
72                 tokens.push(new Token(stream.next(), "TOKN", "UNKNOWN_TOKEN", this.line));
73             }
74             
75             
76             
77             return tokens;
78         },
79
80         /**
81             @returns {Boolean} Was the token found?
82          */
83         read_word : function(/**JSDOC.TokenStream*/stream, tokens) {
84             var found = "";
85             while (!stream.look().eof && Lang.isWordChar(stream.look())) {
86                 found += stream.next();
87             }
88             
89             if (found === "") {
90                 return false;
91             }
92             
93             var name;
94             if ((name = Lang.keyword(found))) {
95                 if (found == 'return' && tokens.lastSym().data == ')') {
96                     throw {
97                         name : "ArgumentError", 
98                         message: "\n" + this.filename + ':' + this.line + " Error - return found after )"
99                     }   
100                 }
101                 
102                 tokens.push(new Token(found, "KEYW", name, this.line));
103                 return true;
104             }
105             if (!this.sepIdents || found.indexOf('.') < 0 ) {
106                 tokens.push(new Token(found, "NAME", "NAME", this.line));
107                 return true;
108             }
109             var n = found.split('.');
110             var p = false;
111             var _this = this;
112             n.forEach(function(nm) {
113                 if (p) {
114                     tokens.push(new Token('.', "PUNC", "DOT", _this.line));
115                 }
116                 p=true;
117                 tokens.push(new Token(nm, "NAME", "NAME", _this.line));
118             });
119             return true;
120                 
121
122         },
123
124         /**
125             @returns {Boolean} Was the token found?
126          */
127         read_punc : function(/**JSDOC.TokenStream*/stream, tokens) {
128             var found = "";
129             var name;
130             while (!stream.look().eof && Lang.punc(found+stream.look())) {
131                 found += stream.next();
132             }
133             
134             
135             if (found === "") {
136                 return false;
137             }
138             
139             if ((found == '}' || found == ']') && tokens.lastSym().data == ',') {
140                 //print("Error - comma found before " + found);
141                 //print(JSON.stringify(tokens.lastSym(), null,4));
142                 throw {
143                     name : "ArgumentError", 
144                     message: "\n" + this.filename + ':' + this.line + " Error - comma found before " + found
145                 }   
146             }
147             
148             tokens.push(new Token(found, "PUNC", Lang.punc(found), this.line));
149             return true;
150             
151         },
152
153         /**
154             @returns {Boolean} Was the token found?
155          */
156         read_space : function(/**JSDOC.TokenStream*/stream, tokens) {
157             var found = "";
158             
159             while (!stream.look().eof && Lang.isSpace(stream.look()) && !Lang.isNewline(stream.look())) {
160                 found += stream.next();
161             }
162             
163             if (found === "") {
164                 return false;
165             }
166             //print("WHITE = " + JSON.stringify(found)); 
167             if (this.collapseWhite) found = " ";
168             if (this.keepWhite) tokens.push(new Token(found, "WHIT", "SPACE", this.line));
169             return true;
170         
171         },
172
173         /**
174             @returns {Boolean} Was the token found?
175          */
176         read_newline : function(/**JSDOC.TokenStream*/stream, tokens) {
177             var found = "";
178             var line = this.line;
179             while (!stream.look().eof && Lang.isNewline(stream.look())) {
180                 this.line++;
181                 found += stream.next();
182             }
183             
184             if (found === "") {
185                 return false;
186             }
187             //this.line++;
188             if (this.collapseWhite) {
189                 found = "\n";
190             }
191             if (this.keepWhite) {
192                 var last = tokens.pop();
193                 if (last && last.name != "WHIT") {
194                     tokens.push(last);
195                 }
196                 
197                 tokens.push(new Token(found, "WHIT", "NEWLINE", line));
198             }
199             return true;
200         },
201
202         /**
203             @returns {Boolean} Was the token found?
204          */
205         read_mlcomment : function(/**JSDOC.TokenStream*/stream, tokens) {
206             if (stream.look() == "/" && stream.look(1) == "*") {
207                 var found = stream.next(2);
208                 var c = '';
209                 var line = this.line;
210                 while (!stream.look().eof && !(stream.look(-1) == "/" && stream.look(-2) == "*")) {
211                     c = stream.next();
212                     if (c == "\n") this.line++;
213                     found += c;
214                 }
215                 
216                 // to start doclet we allow /** or /*** but not /**/ or /****
217                 if (/^\/\*\*([^\/]|\*[^*])/.test(found) && this.keepDocs) tokens.push(new Token(found, "COMM", "JSDOC", this.line));
218                 else if (this.keepComments) tokens.push(new Token(found, "COMM", "MULTI_LINE_COMM", line));
219                 return true;
220             }
221             return false;
222         },
223
224         /**
225             @returns {Boolean} Was the token found?
226          */
227         read_slcomment : function(/**JSDOC.TokenStream*/stream, tokens) {
228             var found;
229             if (
230                 (stream.look() == "/" && stream.look(1) == "/" && (found=stream.next(2)))
231                 || 
232                 (stream.look() == "<" && stream.look(1) == "!" && stream.look(2) == "-" && stream.look(3) == "-" && (found=stream.next(4)))
233             ) {
234                 var line = this.line;
235                 while (!stream.look().eof && !Lang.isNewline(stream.look())) {
236                     found += stream.next();
237                 }
238                 if (!stream.look().eof) {
239                     found += stream.next();
240                 }
241                 if (this.keepComments) {
242                     tokens.push(new Token(found, "COMM", "SINGLE_LINE_COMM", line));
243                 }
244                 this.line++;
245                 return true;
246             }
247             return false;
248         },
249
250         /**
251             @returns {Boolean} Was the token found?
252          */
253         read_dbquote : function(/**JSDOC.TokenStream*/stream, tokens) {
254             if (stream.look() == "\"") {
255                 // find terminator
256                 var string = stream.next();
257                 
258                 while (!stream.look().eof) {
259                     if (stream.look() == "\\") {
260                         if (Lang.isNewline(stream.look(1))) {
261                             do {
262                                 stream.next();
263                             } while (!stream.look().eof && Lang.isNewline(stream.look()));
264                             string += "\\\n";
265                         }
266                         else {
267                             string += stream.next(2);
268                         }
269                     }
270                     else if (stream.look() == "\"") {
271                         string += stream.next();
272                         tokens.push(new Token(string, "STRN", "DOUBLE_QUOTE", this.line));
273                         return true;
274                     }
275                     else {
276                         string += stream.next();
277                     }
278                 }
279             }
280             return false; // error! unterminated string
281         },
282
283         /**
284             @returns {Boolean} Was the token found?
285          */
286         read_snquote : function(/**JSDOC.TokenStream*/stream, tokens) {
287             if (stream.look() == "'") {
288                 // find terminator
289                 var string = stream.next();
290                 
291                 while (!stream.look().eof) {
292                     if (stream.look() == "\\") { // escape sequence
293                         string += stream.next(2);
294                     }
295                     else if (stream.look() == "'") {
296                         string += stream.next();
297                         tokens.push(new Token(string, "STRN", "SINGLE_QUOTE", this.line));
298                         return true;
299                     }
300                     else {
301                         string += stream.next();
302                     }
303                 }
304             }
305             return false; // error! unterminated string
306         },
307
308         /**
309             @returns {Boolean} Was the token found?
310          */
311         read_numb : function(/**JSDOC.TokenStream*/stream, tokens) {
312             if (stream.look() === "0" && stream.look(1) == "x") {
313                 return this.read_hex(stream, tokens);
314             }
315             
316             var found = "";
317             
318             while (!stream.look().eof && Lang.isNumber(found+stream.look())){
319                 found += stream.next();
320             }
321             
322             if (found === "") {
323                 return false;
324             }
325             else {
326                 if (/^0[0-7]/.test(found)) tokens.push(new Token(found, "NUMB", "OCTAL", this.line));
327                 else tokens.push(new Token(found, "NUMB", "DECIMAL", this.line));
328                 return true;
329             }
330         },
331         /*t:
332             requires("../lib/JSDOC/TextStream.js");
333             requires("../lib/JSDOC/Token.js");
334             requires("../lib/JSDOC/Lang.js");
335             
336             plan(3, "testing read_numb");
337             
338             //// setup
339             var src = "function foo(num){while (num+8.0 >= 0x20 && num < 0777){}}";
340             var tr = new TokenReader();
341             var tokens = tr.tokenize(new TextStream(src));
342             
343             var hexToken, octToken, decToken;
344             for (var i = 0; i < tokens.length; i++) {
345                 if (tokens[i].name == "HEX_DEC") hexToken = tokens[i];
346                 if (tokens[i].name == "OCTAL") octToken = tokens[i];
347                 if (tokens[i].name == "DECIMAL") decToken = tokens[i];
348             }
349             ////
350             
351             is(decToken.data, "8.0", "decimal number is found in source.");
352             is(hexToken.data, "0x20", "hexdec number is found in source (issue #99).");
353             is(octToken.data, "0777", "octal number is found in source.");
354         */
355
356         /**
357             @returns {Boolean} Was the token found?
358          */
359         read_hex : function(/**JSDOC.TokenStream*/stream, tokens) {
360             var found = stream.next(2);
361             
362             while (!stream.look().eof) {
363                 if (Lang.isHexDec(found) && !Lang.isHexDec(found+stream.look())) { // done
364                     tokens.push(new Token(found, "NUMB", "HEX_DEC", this.line));
365                     return true;
366                 }
367                 else {
368                     found += stream.next();
369                 }
370             }
371             return false;
372         },
373
374         /**
375             @returns {Boolean} Was the token found?
376          */
377         read_regx : function(/**JSDOC.TokenStream*/stream, tokens) {
378             var last;
379             if (
380                 stream.look() == "/"
381                 && 
382                 (
383                     
384                     (
385                         !(last = tokens.lastSym()) // there is no last, the regex is the first symbol
386                         || 
387                         (
388                                !last.is("NUMB")
389                             && !last.is("NAME")
390                             && !last.is("RIGHT_PAREN")
391                             && !last.is("RIGHT_BRACKET")
392                         )
393                     )
394                 )
395             ) {
396                 var regex = stream.next();
397                 
398                 while (!stream.look().eof) {
399                     if (stream.look() == "\\") { // escape sequence
400                         regex += stream.next(2);
401                     }
402                     else if (stream.look() == "/") {
403                         regex += stream.next();
404                         
405                         while (/[gmi]/.test(stream.look())) {
406                             regex += stream.next();
407                         }
408                         
409                         tokens.push(new Token(regex, "REGX", "REGX", this.line));
410                         return true;
411                     }
412                     else {
413                         regex += stream.next();
414                     }
415                 }
416                 // error: unterminated regex
417             }
418             return false;
419         }
420 });