]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
Improve diff display in case the whole key in missing
[rust.git] / src / tools / rustdoc-js / tester.js
1 const fs = require('fs');
2 const path = require('path');
3
4 function getNextStep(content, pos, stop) {
5     while (pos < content.length && content[pos] !== stop &&
6            (content[pos] === ' ' || content[pos] === '\t' || content[pos] === '\n')) {
7         pos += 1;
8     }
9     if (pos >= content.length) {
10         return null;
11     }
12     if (content[pos] !== stop) {
13         return pos * -1;
14     }
15     return pos;
16 }
17
18 // Stupid function extractor based on indent. Doesn't support block
19 // comments. If someone puts a ' or an " in a block comment this
20 // will blow up. Template strings are not tested and might also be
21 // broken.
22 function extractFunction(content, functionName) {
23     var indent = 0;
24     var splitter = "function " + functionName + "(";
25
26     while (true) {
27         var start = content.indexOf(splitter);
28         if (start === -1) {
29             break;
30         }
31         var pos = start;
32         while (pos < content.length && content[pos] !== ')') {
33             pos += 1;
34         }
35         if (pos >= content.length) {
36             break;
37         }
38         pos = getNextStep(content, pos + 1, '{');
39         if (pos === null) {
40             break;
41         } else if (pos < 0) {
42             content = content.slice(-pos);
43             continue;
44         }
45         while (pos < content.length) {
46             // Eat single-line comments
47             if (content[pos] === '/' && pos > 0 && content[pos-1] === '/') {
48                 do {
49                     pos += 1;
50                 } while (pos < content.length && content[pos] !== '\n');
51
52             // Eat quoted strings
53             } else if (content[pos] === '"' || content[pos] === "'" || content[pos] === "`") {
54                 var stop = content[pos];
55                 var is_escaped = false;
56                 do {
57                     if (content[pos] === '\\') {
58                         pos += 2;
59                     } else {
60                         pos += 1;
61                     }
62                 } while (pos < content.length &&
63                          (content[pos] !== stop || content[pos - 1] === '\\'));
64
65             // Otherwise, check for indent
66             } else if (content[pos] === '{') {
67                 indent += 1;
68             } else if (content[pos] === '}') {
69                 indent -= 1;
70                 if (indent === 0) {
71                     return content.slice(start, pos + 1);
72                 }
73             }
74             pos += 1;
75         }
76         content = content.slice(start + 1);
77     }
78     return null;
79 }
80
81 // Stupid function extractor for array.
82 function extractArrayVariable(content, arrayName) {
83     var splitter = "var " + arrayName;
84     while (true) {
85         var start = content.indexOf(splitter);
86         if (start === -1) {
87             break;
88         }
89         var pos = getNextStep(content, start, '=');
90         if (pos === null) {
91             break;
92         } else if (pos < 0) {
93             content = content.slice(-pos);
94             continue;
95         }
96         pos = getNextStep(content, pos, '[');
97         if (pos === null) {
98             break;
99         } else if (pos < 0) {
100             content = content.slice(-pos);
101             continue;
102         }
103         while (pos < content.length) {
104             if (content[pos] === '"' || content[pos] === "'") {
105                 var stop = content[pos];
106                 do {
107                     if (content[pos] === '\\') {
108                         pos += 2;
109                     } else {
110                         pos += 1;
111                     }
112                 } while (pos < content.length &&
113                          (content[pos] !== stop || content[pos - 1] === '\\'));
114             } else if (content[pos] === ']' &&
115                        pos + 1 < content.length &&
116                        content[pos + 1] === ';') {
117                 return content.slice(start, pos + 2);
118             }
119             pos += 1;
120         }
121         content = content.slice(start + 1);
122     }
123     return null;
124 }
125
126 // Stupid function extractor for variable.
127 function extractVariable(content, varName) {
128     var splitter = "var " + varName;
129     while (true) {
130         var start = content.indexOf(splitter);
131         if (start === -1) {
132             break;
133         }
134         var pos = getNextStep(content, start, '=');
135         if (pos === null) {
136             break;
137         } else if (pos < 0) {
138             content = content.slice(-pos);
139             continue;
140         }
141         while (pos < content.length) {
142             if (content[pos] === '"' || content[pos] === "'") {
143                 var stop = content[pos];
144                 do {
145                     if (content[pos] === '\\') {
146                         pos += 2;
147                     } else {
148                         pos += 1;
149                     }
150                 } while (pos < content.length &&
151                          (content[pos] !== stop || content[pos - 1] === '\\'));
152             } else if (content[pos] === ';' || content[pos] === ',') {
153                 return content.slice(start, pos + 1);
154             }
155             pos += 1;
156         }
157         content = content.slice(start + 1);
158     }
159     return null;
160 }
161
162 function loadContent(content) {
163     var Module = module.constructor;
164     var m = new Module();
165     m._compile(content, "tmp.js");
166     m.exports.ignore_order = content.indexOf("\n// ignore-order\n") !== -1 ||
167         content.startsWith("// ignore-order\n");
168     m.exports.exact_check = content.indexOf("\n// exact-check\n") !== -1 ||
169         content.startsWith("// exact-check\n");
170     m.exports.should_fail = content.indexOf("\n// should-fail\n") !== -1 ||
171         content.startsWith("// should-fail\n");
172     return m.exports;
173 }
174
175 function readFile(filePath) {
176     return fs.readFileSync(filePath, 'utf8');
177 }
178
179 function loadThings(thingsToLoad, kindOfLoad, funcToCall, fileContent) {
180     var content = '';
181     for (var i = 0; i < thingsToLoad.length; ++i) {
182         var tmp = funcToCall(fileContent, thingsToLoad[i]);
183         if (tmp === null) {
184             console.log('unable to find ' + kindOfLoad + ' "' + thingsToLoad[i] + '"');
185             process.exit(1);
186         }
187         content += tmp;
188         content += 'exports.' + thingsToLoad[i] + ' = ' + thingsToLoad[i] + ';';
189     }
190     return content;
191 }
192
193 function contentToDiffLine(key, value) {
194     return `"${key}": "${value}",`;
195 }
196
197 // This function is only called when no matching result was found and therefore will only display
198 // the diff between the two items.
199 function betterLookingDiff(entry, data) {
200     let output = ' {\n';
201     let spaces = '     ';
202     for (let key in entry) {
203         if (!entry.hasOwnProperty(key)) {
204             continue;
205         }
206         if (!data || !data.hasOwnProperty(key)) {
207             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
208             continue;
209         }
210         let value = data[key];
211         if (value !== entry[key]) {
212             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
213             output += '+' + spaces + contentToDiffLine(key, value) + '\n';
214         } else {
215             output += spaces + contentToDiffLine(key, value) + '\n';
216         }
217     }
218     return output + ' }';
219 }
220
221 function lookForEntry(entry, data) {
222     for (var i = 0; i < data.length; ++i) {
223         var allGood = true;
224         for (var key in entry) {
225             if (!entry.hasOwnProperty(key)) {
226                 continue;
227             }
228             var value = data[i][key];
229             // To make our life easier, if there is a "parent" type, we add it to the path.
230             if (key === 'path' && data[i]['parent'] !== undefined) {
231                 if (value.length > 0) {
232                     value += '::' + data[i]['parent']['name'];
233                 } else {
234                     value = data[i]['parent']['name'];
235                 }
236             }
237             if (value !== entry[key]) {
238                 allGood = false;
239                 break;
240             }
241         }
242         if (allGood === true) {
243             return i;
244         }
245     }
246     return null;
247 }
248
249 function loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate) {
250     if (searchIndex[searchIndex.length - 1].length === 0) {
251         searchIndex.pop();
252     }
253     searchIndex.pop();
254     var fullSearchIndex = searchIndex.join("\n") + '\nexports.rawSearchIndex = searchIndex;';
255     searchIndex = loadContent(fullSearchIndex);
256     var finalJS = "";
257
258     var arraysToLoad = ["itemTypes"];
259     var variablesToLoad = ["MAX_LEV_DISTANCE", "MAX_RESULTS", "NO_TYPE_FILTER",
260                            "GENERICS_DATA", "NAME", "INPUTS_DATA", "OUTPUT_DATA",
261                            "TY_PRIMITIVE", "TY_KEYWORD",
262                            "levenshtein_row2"];
263     // execQuery first parameter is built in getQuery (which takes in the search input).
264     // execQuery last parameter is built in buildIndex.
265     // buildIndex requires the hashmap from search-index.
266     var functionsToLoad = ["buildHrefAndPath", "pathSplitter", "levenshtein", "validateResult",
267                            "handleAliases", "getQuery", "buildIndex", "execQuery", "execSearch"];
268
269     ALIASES = {};
270     finalJS += 'window = { "currentCrate": "' + crate + '", rootPath: "../" };\n';
271     finalJS += loadThings(["hasOwnProperty", "onEach"], 'function', extractFunction, storageJs);
272     finalJS += loadThings(arraysToLoad, 'array', extractArrayVariable, mainJs);
273     finalJS += loadThings(variablesToLoad, 'variable', extractVariable, mainJs);
274     finalJS += loadThings(functionsToLoad, 'function', extractFunction, mainJs);
275
276     var loaded = loadContent(finalJS);
277     var index = loaded.buildIndex(searchIndex.rawSearchIndex);
278
279     return [loaded, index];
280 }
281
282 function runSearch(query, expected, index, loaded, loadedFile, queryName) {
283     const filter_crate = loadedFile.FILTER_CRATE;
284     const ignore_order = loadedFile.ignore_order;
285     const exact_check = loadedFile.exact_check;
286
287     var results = loaded.execSearch(loaded.getQuery(query), index, filter_crate);
288     var error_text = [];
289
290     for (var key in expected) {
291         if (!expected.hasOwnProperty(key)) {
292             continue;
293         }
294         if (!results.hasOwnProperty(key)) {
295             error_text.push('==> Unknown key "' + key + '"');
296             break;
297         }
298         var entry = expected[key];
299
300         if (exact_check == true && entry.length !== results[key].length) {
301             error_text.push(queryName + "==> Expected exactly " + entry.length +
302                             " results but found " + results[key].length + " in '" + key + "'");
303         }
304
305         var prev_pos = -1;
306         for (var i = 0; i < entry.length; ++i) {
307             var entry_pos = lookForEntry(entry[i], results[key]);
308             if (entry_pos === null) {
309                 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
310                                 JSON.stringify(entry[i]) + "'");
311                 // By default, we just compare the two first items.
312                 let item_to_diff = 0;
313                 if ((ignore_order === false || exact_check === true) && i < results[key].length) {
314                     item_to_diff = i;
315                 }
316                 error_text.push("Diff of first error:\n" +
317                     betterLookingDiff(entry[i], results[key][item_to_diff]));
318             } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
319                 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
320                                 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
321                                 JSON.stringify(results[key][i]) + "'");
322             } else if (ignore_order === false && entry_pos < prev_pos) {
323                 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
324                                 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
325             } else {
326                 prev_pos = entry_pos;
327             }
328         }
329     }
330     return error_text;
331 }
332
333 function checkResult(error_text, loadedFile, displaySuccess) {
334     if (error_text.length === 0 && loadedFile.should_fail === true) {
335         console.log("FAILED");
336         console.log("==> Test was supposed to fail but all items were found...");
337     } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
338         console.log("FAILED");
339         console.log(error_text.join("\n"));
340     } else {
341         if (displaySuccess) {
342             console.log("OK");
343         }
344         return 0;
345     }
346     return 1;
347 }
348
349 function runChecks(testFile, loaded, index) {
350     var testFileContent = readFile(testFile) + 'exports.QUERY = QUERY;exports.EXPECTED = EXPECTED;';
351     if (testFileContent.indexOf("FILTER_CRATE") !== -1) {
352         testFileContent += "exports.FILTER_CRATE = FILTER_CRATE;";
353     }
354     var loadedFile = loadContent(testFileContent);
355
356     const expected = loadedFile.EXPECTED;
357     const query = loadedFile.QUERY;
358
359     if (Array.isArray(query)) {
360         if (!Array.isArray(expected)) {
361             console.log("FAILED");
362             console.log("==> If QUERY variable is an array, EXPECTED should be an array too");
363             return 1;
364         } else if (query.length !== expected.length) {
365             console.log("FAILED");
366             console.log("==> QUERY variable should have the same length as EXPECTED");
367             return 1;
368         }
369         for (var i = 0; i < query.length; ++i) {
370             var error_text = runSearch(query[i], expected[i], index, loaded, loadedFile,
371                 "[ query `" + query[i] + "`]");
372             if (checkResult(error_text, loadedFile, false) !== 0) {
373                 return 1;
374             }
375         }
376         console.log("OK");
377         return 0;
378     }
379     var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
380     return checkResult(error_text, loadedFile, true);
381 }
382
383 function load_files(doc_folder, resource_suffix, crate) {
384     var mainJs = readFile(path.join(doc_folder, "main" + resource_suffix + ".js"));
385     var storageJs = readFile(path.join(doc_folder, "storage" + resource_suffix + ".js"));
386     var searchIndex = readFile(
387         path.join(doc_folder, "search-index" + resource_suffix + ".js")).split("\n");
388
389     return loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate);
390 }
391
392 function showHelp() {
393     console.log("rustdoc-js options:");
394     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
395     console.log("  --help                     : show this message then quit");
396     console.log("  --crate-name [STRING]      : crate name to be used");
397     console.log("  --test-file [PATH]         : location of the JS test file");
398     console.log("  --test-folder [PATH]       : location of the JS tests folder");
399     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
400 }
401
402 function parseOptions(args) {
403     var opts = {
404         "crate_name": "",
405         "resource_suffix": "",
406         "doc_folder": "",
407         "test_folder": "",
408         "test_file": "",
409     };
410     var correspondances = {
411         "--resource-suffix": "resource_suffix",
412         "--doc-folder": "doc_folder",
413         "--test-folder": "test_folder",
414         "--test-file": "test_file",
415         "--crate-name": "crate_name",
416     };
417
418     for (var i = 0; i < args.length; ++i) {
419         if (args[i] === "--resource-suffix"
420             || args[i] === "--doc-folder"
421             || args[i] === "--test-folder"
422             || args[i] === "--test-file"
423             || args[i] === "--crate-name") {
424             i += 1;
425             if (i >= args.length) {
426                 console.log("Missing argument after `" + args[i - 1] + "` option.");
427                 return null;
428             }
429             opts[correspondances[args[i - 1]]] = args[i];
430         } else if (args[i] === "--help") {
431             showHelp();
432             process.exit(0);
433         } else {
434             console.log("Unknown option `" + args[i] + "`.");
435             console.log("Use `--help` to see the list of options");
436             return null;
437         }
438     }
439     if (opts["doc_folder"].length < 1) {
440         console.log("Missing `--doc-folder` option.");
441     } else if (opts["crate_name"].length < 1) {
442         console.log("Missing `--crate-name` option.");
443     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
444         console.log("At least one of `--test-folder` or `--test-file` option is required.");
445     } else {
446         return opts;
447     }
448     return null;
449 }
450
451 function checkFile(test_file, opts, loaded, index) {
452     const test_name = path.basename(test_file, ".js");
453
454     process.stdout.write('Checking "' + test_name + '" ... ');
455     return runChecks(test_file, loaded, index);
456 }
457
458 function main(argv) {
459     var opts = parseOptions(argv.slice(2));
460     if (opts === null) {
461         return 1;
462     }
463
464     var [loaded, index] = load_files(
465         opts["doc_folder"],
466         opts["resource_suffix"],
467         opts["crate_name"]);
468     var errors = 0;
469
470     if (opts["test_file"].length !== 0) {
471         errors += checkFile(opts["test_file"], opts, loaded, index);
472     }
473     if (opts["test_folder"].length !== 0) {
474         fs.readdirSync(opts["test_folder"]).forEach(function(file) {
475             if (!file.endsWith(".js")) {
476                 return;
477             }
478             errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
479         });
480     }
481     return errors > 0 ? 1 : 0;
482 }
483
484 process.exit(main(process.argv));