Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / devtools / front_end / ScriptFormatterWorker.js
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 importScripts("utilities.js");
31 importScripts("cm/headlesscodemirror.js");
32 importScripts("cm/css.js");
33 importScripts("cm/javascript.js");
34 importScripts("cm/xml.js");
35 importScripts("cm/htmlmixed.js");
36 WebInspector = {};
37 FormatterWorker = {
38     /**
39      * @param {string} mimeType
40      * @return {function(string, function(string, ?string, number, number))}
41      */
42     createTokenizer: function(mimeType)
43     {
44         var mode = CodeMirror.getMode({indentUnit: 2}, mimeType);
45         var state = CodeMirror.startState(mode);
46         function tokenize(line, callback)
47         {
48             var stream = new CodeMirror.StringStream(line);
49             while (!stream.eol()) {
50                 var style = mode.token(stream, state);
51                 var value = stream.current();
52                 callback(value, style, stream.start, stream.start + value.length);
53                 stream.start = stream.pos;
54             }
55         }
56         return tokenize;
57     }
58 };
59
60 /**
61  * @typedef {{indentString: string, content: string, mimeType: string}}
62  */
63 var FormatterParameters;
64
65 var onmessage = function(event) {
66     var data = /** @type !{method: string, params: !FormatterParameters} */ (event.data);
67     if (!data.method)
68         return;
69
70     FormatterWorker[data.method](data.params);
71 };
72
73 /**
74  * @param {!FormatterParameters} params
75  */
76 FormatterWorker.format = function(params)
77 {
78     // Default to a 4-space indent.
79     var indentString = params.indentString || "    ";
80     var result = {};
81
82     if (params.mimeType === "text/html") {
83         var formatter = new FormatterWorker.HTMLFormatter(indentString);
84         result = formatter.format(params.content);
85     } else if (params.mimeType === "text/css") {
86         result.mapping = { original: [0], formatted: [0] };
87         result.content = FormatterWorker._formatCSS(params.content, result.mapping, 0, 0, indentString);
88     } else {
89         result.mapping = { original: [0], formatted: [0] };
90         result.content = FormatterWorker._formatScript(params.content, result.mapping, 0, 0, indentString);
91     }
92     postMessage(result);
93 }
94
95 /**
96  * @param {number} totalLength
97  * @param {number} chunkSize
98  */
99 FormatterWorker._chunkCount = function(totalLength, chunkSize)
100 {
101     if (totalLength <= chunkSize)
102         return 1;
103
104     var remainder = totalLength % chunkSize;
105     var partialLength = totalLength - remainder;
106     return (partialLength / chunkSize) + (remainder ? 1 : 0);
107 }
108
109 /**
110  * @param {!Object} params
111  */
112 FormatterWorker.javaScriptOutline = function(params)
113 {
114     var chunkSize = 100000; // characters per data chunk
115     var totalLength = params.content.length;
116     var lines = params.content.split("\n");
117     var chunkCount = FormatterWorker._chunkCount(totalLength, chunkSize);
118     var outlineChunk = [];
119     var previousIdentifier = null;
120     var previousToken = null;
121     var previousTokenType = null;
122     var currentChunk = 1;
123     var processedChunkCharacters = 0;
124     var addedFunction = false;
125     var isReadingArguments = false;
126     var argumentsText = "";
127     var currentFunction = null;
128     var tokenizer = FormatterWorker.createTokenizer("text/javascript");
129     for (var i = 0; i < lines.length; ++i) {
130         var line = lines[i];
131         tokenizer(line, processToken);
132     }
133
134     /**
135      * @param {?string} tokenType
136      * @return {boolean}
137      */
138     function isJavaScriptIdentifier(tokenType)
139     {
140         if (!tokenType)
141             return false;
142         return tokenType.startsWith("variable") || tokenType.startsWith("property") || tokenType === "def";
143     }
144
145     /**
146      * @param {string} tokenValue
147      * @param {?string} tokenType
148      * @param {number} column
149      * @param {number} newColumn
150      */
151     function processToken(tokenValue, tokenType, column, newColumn)
152     {
153         if (isJavaScriptIdentifier(tokenType)) {
154             previousIdentifier = tokenValue;
155             if (tokenValue && previousToken === "function") {
156                 // A named function: "function f...".
157                 currentFunction = { line: i, column: column, name: tokenValue };
158                 addedFunction = true;
159                 previousIdentifier = null;
160             }
161         } else if (tokenType === "keyword") {
162             if (tokenValue === "function") {
163                 if (previousIdentifier && (previousToken === "=" || previousToken === ":")) {
164                     // Anonymous function assigned to an identifier: "...f = function..."
165                     // or "funcName: function...".
166                     currentFunction = { line: i, column: column, name: previousIdentifier };
167                     addedFunction = true;
168                     previousIdentifier = null;
169                 }
170             }
171         } else if (tokenValue === "." && isJavaScriptIdentifier(previousTokenType))
172             previousIdentifier += ".";
173         else if (tokenValue === "(" && addedFunction)
174             isReadingArguments = true;
175         if (isReadingArguments && tokenValue)
176             argumentsText += tokenValue;
177
178         if (tokenValue === ")" && isReadingArguments) {
179             addedFunction = false;
180             isReadingArguments = false;
181             currentFunction.arguments = argumentsText.replace(/,[\r\n\s]*/g, ", ").replace(/([^,])[\r\n\s]+/g, "$1");
182             argumentsText = "";
183             outlineChunk.push(currentFunction);
184         }
185
186         if (tokenValue.trim().length) {
187             // Skip whitespace tokens.
188             previousToken = tokenValue;
189             previousTokenType = tokenType;
190         }
191         processedChunkCharacters += newColumn - column;
192
193         if (processedChunkCharacters >= chunkSize) {
194             postMessage({ chunk: outlineChunk, total: chunkCount, index: currentChunk++ });
195             outlineChunk = [];
196             processedChunkCharacters = 0;
197         }
198     }
199
200     postMessage({ chunk: outlineChunk, total: chunkCount, index: chunkCount });
201 }
202
203 FormatterWorker.CSSParserStates = {
204     Initial: "Initial",
205     Selector: "Selector",
206     AtRule: "AtRule",
207 };
208
209 FormatterWorker.cssOutline = function(params)
210 {
211     var chunkSize = 100000; // characters per data chunk
212     var totalLength = params.content.length;
213     var lines = params.content.split("\n");
214     var chunkCount = FormatterWorker._chunkCount(totalLength, chunkSize);
215     var rules = [];
216     var processedChunkCharacters = 0;
217     var currentChunk = 0;
218
219     var state = FormatterWorker.CSSParserStates.Initial;
220     var rule;
221     var property;
222
223     /**
224      * @param {string} tokenValue
225      * @param {?string} tokenType
226      * @param {number} column
227      * @param {number} newColumn
228      */
229     function processToken(tokenValue, tokenType, column, newColumn)
230     {
231         switch (state) {
232         case FormatterWorker.CSSParserStates.Initial:
233             if (tokenType === "qualifier" || tokenType === "builtin" || tokenType === "tag") {
234                 rule = {
235                     selectorText: tokenValue,
236                     lineNumber: lineNumber,
237                     columNumber: column,
238                 };
239                 state = FormatterWorker.CSSParserStates.Selector;
240             } else if (tokenType === "def") {
241                 rule = {
242                     atRule: tokenValue,
243                     lineNumber: lineNumber,
244                     columNumber: column,
245                 };
246                 state = FormatterWorker.CSSParserStates.AtRule;
247             }
248             break;
249         case FormatterWorker.CSSParserStates.Selector:
250             if (tokenValue === "{" && tokenType === null) {
251                 rule.selectorText = rule.selectorText.trim();
252                 rules.push(rule);
253                 state = FormatterWorker.CSSParserStates.Initial;
254             } else {
255                 rule.selectorText += tokenValue;
256             }
257             break;
258         case FormatterWorker.CSSParserStates.AtRule:
259             if ((tokenValue === ";" || tokenValue === "{") && tokenType === null) {
260                 rule.atRule = rule.atRule.trim();
261                 rules.push(rule);
262                 state = FormatterWorker.CSSParserStates.Initial;
263             } else {
264                 rule.atRule += tokenValue;
265             }
266             break;
267         default:
268             console.assert(false, "Unknown CSS parser state.");
269         }
270         processedChunkCharacters += newColumn - column;
271         if (processedChunkCharacters > chunkSize) {
272             postMessage({ chunk: rules, total: chunkCount, index: currentChunk++ });
273             rules = [];
274             processedChunkCharacters = 0;
275         }
276     }
277     var tokenizer = FormatterWorker.createTokenizer("text/css");
278     var lineNumber;
279     for (lineNumber = 0; lineNumber < lines.length; ++lineNumber) {
280         var line = lines[lineNumber];
281         tokenizer(line, processToken);
282     }
283     postMessage({ chunk: rules, total: chunkCount, index: currentChunk++ });
284 }
285
286 /**
287  * @param {string} content
288  * @param {!{original: !Array.<number>, formatted: !Array.<number>}} mapping
289  * @param {number} offset
290  * @param {number} formattedOffset
291  * @param {string} indentString
292  * @return {string}
293  */
294 FormatterWorker._formatScript = function(content, mapping, offset, formattedOffset, indentString)
295 {
296     var formattedContent;
297     try {
298         var tokenizer = new FormatterWorker.JavaScriptTokenizer(content);
299         var builder = new FormatterWorker.JavaScriptFormattedContentBuilder(tokenizer.content(), mapping, offset, formattedOffset, indentString);
300         var formatter = new FormatterWorker.JavaScriptFormatter(tokenizer, builder);
301         formatter.format();
302         formattedContent = builder.content();
303     } catch (e) {
304         formattedContent = content;
305     }
306     return formattedContent;
307 }
308
309 /**
310  * @param {string} content
311  * @param {!{original: !Array.<number>, formatted: !Array.<number>}} mapping
312  * @param {number} offset
313  * @param {number} formattedOffset
314  * @param {string} indentString
315  * @return {string}
316  */
317 FormatterWorker._formatCSS = function(content, mapping, offset, formattedOffset, indentString)
318 {
319     var formattedContent;
320     try {
321         var builder = new FormatterWorker.CSSFormattedContentBuilder(content, mapping, offset, formattedOffset, indentString);
322         var formatter = new FormatterWorker.CSSFormatter(content, builder);
323         formatter.format();
324         formattedContent = builder.content();
325     } catch (e) {
326         formattedContent = content;
327     }
328     return formattedContent;
329 }
330
331 /**
332  * @constructor
333  * @param {string} indentString
334  */
335 FormatterWorker.HTMLFormatter = function(indentString)
336 {
337     this._indentString = indentString;
338 }
339
340 FormatterWorker.HTMLFormatter.prototype = {
341     /**
342      * @param {string} content
343      * @return {!{content: string, mapping: {original: !Array.<number>, formatted: !Array.<number>}}}
344      */
345     format: function(content)
346     {
347         this.line = content;
348         this._content = content;
349         this._formattedContent = "";
350         this._mapping = { original: [0], formatted: [0] };
351         this._position = 0;
352
353         var scriptOpened = false;
354         var styleOpened = false;
355         var tokenizer = FormatterWorker.createTokenizer("text/html");
356
357         /**
358          * @this {FormatterWorker.HTMLFormatter}
359          */
360         function processToken(tokenValue, tokenType, tokenStart, tokenEnd) {
361             if (tokenType !== "tag")
362                 return;
363             if (tokenValue.toLowerCase() === "<script") {
364                 scriptOpened = true;
365             } else if (scriptOpened && tokenValue === ">") {
366                 scriptOpened = false;
367                 this._scriptStarted(tokenEnd);
368             } else if (tokenValue.toLowerCase() === "</script") {
369                 this._scriptEnded(tokenStart);
370             } else if (tokenValue.toLowerCase() === "<style") {
371                 styleOpened = true;
372             } else if (styleOpened && tokenValue === ">") {
373                 styleOpened = false;
374                 this._styleStarted(tokenEnd);
375             } else if (tokenValue.toLowerCase() === "</style") {
376                 this._styleEnded(tokenStart);
377             }
378         }
379         tokenizer(content, processToken.bind(this));
380
381         this._formattedContent += this._content.substring(this._position);
382         return { content: this._formattedContent, mapping: this._mapping };
383     },
384
385     /**
386      * @param {number} cursor
387      */
388     _scriptStarted: function(cursor)
389     {
390         this._handleSubFormatterStart(cursor);
391     },
392
393     /**
394      * @param {number} cursor
395      */
396     _scriptEnded: function(cursor)
397     {
398         this._handleSubFormatterEnd(FormatterWorker._formatScript, cursor);
399     },
400
401     /**
402      * @param {number} cursor
403      */
404     _styleStarted: function(cursor)
405     {
406         this._handleSubFormatterStart(cursor);
407     },
408
409     /**
410      * @param {number} cursor
411      */
412     _styleEnded: function(cursor)
413     {
414         this._handleSubFormatterEnd(FormatterWorker._formatCSS, cursor);
415     },
416
417     /**
418      * @param {number} cursor
419      */
420     _handleSubFormatterStart: function(cursor)
421     {
422         this._formattedContent += this._content.substring(this._position, cursor);
423         this._formattedContent += "\n";
424         this._position = cursor;
425     },
426
427     /**
428      * @param {function(string, !{formatted: !Array.<number>, original: !Array.<number>}, number, number, string)} formatFunction
429      * @param {number} cursor
430      */
431     _handleSubFormatterEnd: function(formatFunction, cursor)
432     {
433         if (cursor === this._position)
434             return;
435
436         var scriptContent = this._content.substring(this._position, cursor);
437         this._mapping.original.push(this._position);
438         this._mapping.formatted.push(this._formattedContent.length);
439         var formattedScriptContent = formatFunction(scriptContent, this._mapping, this._position, this._formattedContent.length, this._indentString);
440
441         this._formattedContent += formattedScriptContent;
442         this._position = cursor;
443     }
444 }
445
446 Array.prototype.keySet = function()
447 {
448     var keys = {};
449     for (var i = 0; i < this.length; ++i)
450         keys[this[i]] = true;
451     return keys;
452 };
453
454 /**
455  * @return {!Object}
456  */
457 function require()
458 {
459     return parse;
460 }
461
462 /**
463  * @type {!{tokenizer}}
464  */
465 var exports = { tokenizer: null };
466 importScripts("UglifyJS/parse-js.js");
467 var parse = exports;
468
469 importScripts("JavaScriptFormatter.js");
470 importScripts("CSSFormatter.js");