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