9c5054da5a2432496947e44153675f7c7317ebed
[gnome.introspection-doc-generator] / JSDOC / TokenReader.vala
1 //<script type="text/javascript">
2
3  
4
5
6 //const Token   = imports.Token.Token;
7 //const Lang    = imports.Lang.Lang;
8
9 /**
10         @class Search a {@link JSDOC.TextStream} for language tokens.
11 */
12
13 namespace JSDOC {
14
15     public class TokenArray: Object {
16         
17         public Gee.ArrayList<Token> tokens;
18         public int length {
19             get { return this.tokens.size }
20         }
21         
22         public TokenArray()
23         {
24             this.items = new Gee.ArrayList<Token>();
25         }
26         
27         public Token? last() {
28             if (this.tokens > 0) {
29                 return this.tokens[this.tokens.length-1];
30             }
31             return null;
32         }
33         public Token? lastSym () {
34             for (var i = this.tokens.length-1; i >= 0; i--) {
35                 if (!(this.tokens.get(i).is("WHIT") || this.tokens.get(i).is("COMM")))  {
36                     return this.tokens.get(i);
37                 }
38             }
39             return null;
40         }
41         public void push (Token t) {
42             this.tokens.add(t);
43         }
44         public Token get(int i) {
45             return this.tokens.get(i);
46         }
47     }
48
49
50     public class TokenReader : Object
51     {
52         
53         
54         
55         /*
56          *
57          * I wonder if this will accept the prop: value, prop2 :value construxtor if we do not define one...
58          */
59         
60         /** @cfg {Boolean} collapseWhite merge multiple whitespace/comments into a single token **/
61         public bool collapseWhite = false, // only reduces white space...
62         /** @cfg {Boolean} keepDocs keep JSDOC comments **/
63         public bool keepDocs = true,
64         /** @cfg {Boolean} keepWhite keep White space **/
65         public bool keepWhite = false,
66         /** @cfg {Boolean} keepComments  keep all comments **/
67         public bool keepComments = false,
68         /** @cfg {Boolean} sepIdents seperate identifiers (eg. a.b.c into ['a', '.', 'b', '.', 'c'] ) **/
69         public bool sepIdents = false,
70         /** @cfg {String} filename name of file being parsed. **/
71         public string filename = "";
72         /** @config {Boolean} ignoreBadGrammer do not throw errors if we find stuff that might break compression **/
73         public bool ignoreBadGrammer = false,
74         
75         
76         int line = 0;
77         
78         /**
79          * tokenize a stream
80          * @return {Array} of tokens
81          * 
82          * ts = new TextStream(File.read(str));
83          * tr = TokenReader({ keepComments : true, keepWhite : true });
84          * tr.tokenize(ts)
85          * 
86          */
87         public TokenArray tokenize(TextStream stream)
88         {
89             this.line =1;
90             var tokens = new TokenArray();
91            
92             bool eof;
93             while (true) {
94                 
95                 stream.look(0, out eof) 
96                 if (eof) {
97                     break;
98                 }
99                 if (this.read_mlcomment(stream, tokens)) continue;
100                 if (this.read_slcomment(stream, tokens)) continue;
101                 if (this.read_dbquote(stream, tokens))   continue;
102                 if (this.read_snquote(stream, tokens))   continue;
103                 if (this.read_regx(stream, tokens))      continue;
104                 if (this.read_numb(stream, tokens))      continue;
105                 if (this.read_punc(stream, tokens))      continue;
106                 if (this.read_newline(stream, tokens))   continue;
107                 if (this.read_space(stream, tokens))     continue;
108                 if (this.read_word(stream, tokens))      continue;
109                 
110                 // if execution reaches here then an error has happened
111                 tokens.push(
112                         new Token(stream.next(), "TOKN", "UNKNOWN_TOKEN", this.line)
113                 );
114             }
115             
116             
117             
118             return tokens;
119         },
120
121         /**
122          * findPuncToken - find the id of a token (previous to current)
123          * need to back check syntax..
124          * 
125          * @arg {Array} tokens the array of tokens.
126          * @arg {String} token data (eg. '(')
127          * @arg {Number} offset where to start reading from
128          * @return {Number} position of token
129          */
130         public int findPuncToken(TokenArray tokens, string data, int n) {
131             n = n || tokens.length -1;
132             var stack = 0;
133             while (n > -1) {
134                 
135                 if (!stack && tokens[n].data == data) {
136                     return n;
137                 }
138                 
139                 if (tokens[n].data  == ')' || tokens[n].data  == '}') {
140                     stack++;
141                     n--;
142                     continue;
143                 }
144                 if (stack && (tokens[n].data  == '{' || tokens[n].data  == '(')) {
145                     stack--;
146                     n--;
147                     continue;
148                 }
149                 
150                 
151                 n--;
152             }
153             return -1;
154         },
155         /**
156          * lastSym - find the last token symbol
157          * need to back check syntax..
158          * 
159          * @arg {Array} tokens the array of tokens.
160          * @arg {Number} offset where to start..
161          * @return {Token} the token
162          */
163         lastSym : function(tokens, n) {
164             for (var i = n-1; i >= 0; i--) {
165                 if (!(tokens[i].is("WHIT") || tokens[i].is("COMM"))) return tokens[i];
166             }
167             return null;
168         },
169         
170          
171         
172         /**
173             @returns {Boolean} Was the token found?
174          */
175         read_word : function(/**JSDOC.TokenStream*/stream, tokens) {
176             var found = "";
177             while (!stream.look().eof && Lang.isWordChar(stream.look())) {
178                 found += stream.next();
179             }
180             
181             if (found === "") {
182                 return false;
183             }
184             
185             var name;
186             if ((name = Lang.keyword(found))) {
187                 if (found == 'return' && tokens.lastSym().data == ')') {
188                     //Seed.print('@' + tokens.length);
189                     var n = this.findPuncToken(tokens, ')');
190                     //Seed.print(')@' + n);
191                     n = this.findPuncToken(tokens, '(', n-1);
192                     //Seed.print('(@' + n);
193                     
194                     var lt = this.lastSym(tokens, n);
195                     print(JSON.stringify(lt));
196                     if (lt.type != 'KEYW' || ['IF', 'WHILE'].indexOf(lt.name) < -1) {
197                         if (!this.ignoreBadGrammer) {
198                             throw {
199                                 name : "ArgumentError", 
200                                 message: "\n" + this.filename + ':' + this.line + " Error - return found after )"
201                             }
202                         }
203                     }
204                     
205                     
206                     
207                 }
208                 
209                 tokens.push(new Token(found, "KEYW", name, this.line));
210                 return true;
211             }
212             if (!this.sepIdents || found.indexOf('.') < 0 ) {
213                 tokens.push(new Token(found, "NAME", "NAME", this.line));
214                 return true;
215             }
216             var n = found.split('.');
217             var p = false;
218             var _this = this;
219             n.forEach(function(nm) {
220                 if (p) {
221                     tokens.push(new Token('.', "PUNC", "DOT", _this.line));
222                 }
223                 p=true;
224                 tokens.push(new Token(nm, "NAME", "NAME", _this.line));
225             });
226             return true;
227                 
228
229         },
230
231         /**
232             @returns {Boolean} Was the token found?
233          */
234         read_punc : function(/**JSDOC.TokenStream*/stream, tokens) {
235             var found = "";
236             var name;
237             while (!stream.look().eof && Lang.punc(found+stream.look())) {
238                 found += stream.next();
239             }
240             
241             
242             if (found === "") {
243                 return false;
244             }
245             
246             if ((found == '}' || found == ']') && tokens.lastSym().data == ',') {
247                 //print("Error - comma found before " + found);
248                 //print(JSON.stringify(tokens.lastSym(), null,4));
249                 if (this.ignoreBadGrammer) {
250                     print("\n" + this.filename + ':' + this.line + " Error - comma found before " + found);
251                 } else {
252                     
253                     throw {
254                         name : "ArgumentError", 
255                         message: "\n" + this.filename + ':' + this.line + " Error - comma found before " + found
256                     }
257                 }
258             }
259             
260             tokens.push(new Token(found, "PUNC", Lang.punc(found), this.line));
261             return true;
262             
263         },
264
265         /**
266             @returns {Boolean} Was the token found?
267          */
268         read_space : function(/**JSDOC.TokenStream*/stream, tokens) {
269             var found = "";
270             
271             while (!stream.look().eof && Lang.isSpace(stream.look()) && !Lang.isNewline(stream.look())) {
272                 found += stream.next();
273             }
274             
275             if (found === "") {
276                 return false;
277             }
278             //print("WHITE = " + JSON.stringify(found)); 
279             if (this.collapseWhite) found = " ";
280             if (this.keepWhite) tokens.push(new Token(found, "WHIT", "SPACE", this.line));
281             return true;
282         
283         },
284
285         /**
286             @returns {Boolean} Was the token found?
287          */
288         read_newline : function(/**JSDOC.TokenStream*/stream, tokens) {
289             var found = "";
290             var line = this.line;
291             while (!stream.look().eof && Lang.isNewline(stream.look())) {
292                 this.line++;
293                 found += stream.next();
294             }
295             
296             if (found === "") {
297                 return false;
298             }
299             //this.line++;
300             if (this.collapseWhite) {
301                 found = "\n";
302             }
303              if (this.keepWhite) {
304                 var last = tokens ? tokens.pop() : false;
305                 if (last && last.name != "WHIT") {
306                     tokens.push(last);
307                 }
308                 
309                 tokens.push(new Token(found, "WHIT", "NEWLINE", line));
310             }
311             return true;
312         },
313
314         /**
315             @returns {Boolean} Was the token found?
316          */
317         read_mlcomment : function(/**JSDOC.TokenStream*/stream, tokens) {
318             if (stream.look() == "/" && stream.look(1) == "*") {
319                 var found = stream.next(2);
320                 var c = '';
321                 var line = this.line;
322                 while (!stream.look().eof && !(stream.look(-1) == "/" && stream.look(-2) == "*")) {
323                     c = stream.next();
324                     if (c == "\n") this.line++;
325                     found += c;
326                 }
327                 
328                 // to start doclet we allow /** or /*** but not /**/ or /****
329                 if (/^\/\*\*([^\/]|\*[^*])/.test(found) && this.keepDocs) tokens.push(new Token(found, "COMM", "JSDOC", this.line));
330                 else if (this.keepComments) tokens.push(new Token(found, "COMM", "MULTI_LINE_COMM", line));
331                 return true;
332             }
333             return false;
334         },
335
336         /**
337             @returns {Boolean} Was the token found?
338          */
339         read_slcomment : function(/**JSDOC.TokenStream*/stream, tokens) {
340             var found;
341             if (
342                 (stream.look() == "/" && stream.look(1) == "/" && (found=stream.next(2)))
343                 || 
344                 (stream.look() == "<" && stream.look(1) == "!" && stream.look(2) == "-" && stream.look(3) == "-" && (found=stream.next(4)))
345             ) {
346                 var line = this.line;
347                 while (!stream.look().eof && !Lang.isNewline(stream.look())) {
348                     found += stream.next();
349                 }
350                 if (!stream.look().eof) {
351                     found += stream.next();
352                 }
353                 if (this.keepComments) {
354                     tokens.push(new Token(found, "COMM", "SINGLE_LINE_COMM", line));
355                 }
356                 this.line++;
357                 return true;
358             }
359             return false;
360         },
361
362         /**
363             @returns {Boolean} Was the token found?
364          */
365         read_dbquote : function(/**JSDOC.TokenStream*/stream, tokens) {
366             if (stream.look() == "\"") {
367                 // find terminator
368                 var string = stream.next();
369                 
370                 while (!stream.look().eof) {
371                     if (stream.look() == "\\") {
372                         if (Lang.isNewline(stream.look(1))) {
373                             do {
374                                 stream.next();
375                             } while (!stream.look().eof && Lang.isNewline(stream.look()));
376                             string += "\\\n";
377                         }
378                         else {
379                             string += stream.next(2);
380                         }
381                     }
382                     else if (stream.look() == "\"") {
383                         string += stream.next();
384                         tokens.push(new Token(string, "STRN", "DOUBLE_QUOTE", this.line));
385                         return true;
386                     }
387                     else {
388                         string += stream.next();
389                     }
390                 }
391             }
392             return false; // error! unterminated string
393         },
394
395         /**
396             @returns {Boolean} Was the token found?
397          */
398         read_snquote : function(/**JSDOC.TokenStream*/stream, tokens) {
399             if (stream.look() == "'") {
400                 // find terminator
401                 var string = stream.next();
402                 
403                 while (!stream.look().eof) {
404                     if (stream.look() == "\\") { // escape sequence
405                         string += stream.next(2);
406                     }
407                     else if (stream.look() == "'") {
408                         string += stream.next();
409                         tokens.push(new Token(string, "STRN", "SINGLE_QUOTE", this.line));
410                         return true;
411                     }
412                     else {
413                         string += stream.next();
414                     }
415                 }
416             }
417             return false; // error! unterminated string
418         },
419
420         /**
421             @returns {Boolean} Was the token found?
422          */
423         read_numb : function(/**JSDOC.TokenStream*/stream, tokens) {
424             if (stream.look() === "0" && stream.look(1) == "x") {
425                 return this.read_hex(stream, tokens);
426             }
427             
428             var found = "";
429             
430             while (!stream.look().eof && Lang.isNumber(found+stream.look())){
431                 found += stream.next();
432             }
433             
434             if (found === "") {
435                 return false;
436             }
437             else {
438                 if (/^0[0-7]/.test(found)) tokens.push(new Token(found, "NUMB", "OCTAL", this.line));
439                 else tokens.push(new Token(found, "NUMB", "DECIMAL", this.line));
440                 return true;
441             }
442         },
443         /*t:
444             requires("../lib/JSDOC/TextStream.js");
445             requires("../lib/JSDOC/Token.js");
446             requires("../lib/JSDOC/Lang.js");
447             
448             plan(3, "testing read_numb");
449             
450             //// setup
451             var src = "function foo(num){while (num+8.0 >= 0x20 && num < 0777){}}";
452             var tr = new TokenReader();
453             var tokens = tr.tokenize(new TextStream(src));
454             
455             var hexToken, octToken, decToken;
456             for (var i = 0; i < tokens.length; i++) {
457                 if (tokens[i].name == "HEX_DEC") hexToken = tokens[i];
458                 if (tokens[i].name == "OCTAL") octToken = tokens[i];
459                 if (tokens[i].name == "DECIMAL") decToken = tokens[i];
460             }
461             ////
462             
463             is(decToken.data, "8.0", "decimal number is found in source.");
464             is(hexToken.data, "0x20", "hexdec number is found in source (issue #99).");
465             is(octToken.data, "0777", "octal number is found in source.");
466         */
467
468         /**
469             @returns {Boolean} Was the token found?
470          */
471         read_hex : function(/**JSDOC.TokenStream*/stream, tokens) {
472             var found = stream.next(2);
473             
474             while (!stream.look().eof) {
475                 if (Lang.isHexDec(found) && !Lang.isHexDec(found+stream.look())) { // done
476                     tokens.push(new Token(found, "NUMB", "HEX_DEC", this.line));
477                     return true;
478                 }
479                 else {
480                     found += stream.next();
481                 }
482             }
483             return false;
484         },
485
486         /**
487             @returns {Boolean} Was the token found?
488          */
489         read_regx : function(/**JSDOC.TokenStream*/stream, tokens) {
490             var last;
491             if (
492                 stream.look() == "/"
493                 && 
494                 (
495                     
496                     (
497                         !(last = tokens.lastSym()) // there is no last, the regex is the first symbol
498                         || 
499                         (
500                                !last.is("NUMB")
501                             && !last.is("NAME")
502                             && !last.is("RIGHT_PAREN")
503                             && !last.is("RIGHT_BRACKET")
504                         )
505                     )
506                 )
507             ) {
508                 var regex = stream.next();
509                 
510                 while (!stream.look().eof) {
511                     if (stream.look() == "\\") { // escape sequence
512                         regex += stream.next(2);
513                     }
514                     else if (stream.look() == "/") {
515                         regex += stream.next();
516                         
517                         while (/[gmi]/.test(stream.look())) {
518                             regex += stream.next();
519                         }
520                         
521                         tokens.push(new Token(regex, "REGX", "REGX", this.line));
522                         return true;
523                     }
524                     else {
525                         regex += stream.next();
526                     }
527                 }
528                 // error: unterminated regex
529             }
530             return false;
531         }
532 });