]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
Rollup merge of #87468 - calebcartwright:update-rustfmt, r=Mark-Simulacrum
[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 loadSearchJsAndIndex(searchJs, 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                            "removeEmptyStringsFromArray"];
269
270     const functions = ["hasOwnPropertyRustdoc", "onEach"];
271     ALIASES = {};
272     finalJS += 'window = { "currentCrate": "' + crate + '", rootPath: "../" };\n';
273     finalJS += loadThings(functions, 'function', extractFunction, storageJs);
274     finalJS += loadThings(arraysToLoad, 'array', extractArrayVariable, searchJs);
275     finalJS += loadThings(variablesToLoad, 'variable', extractVariable, searchJs);
276     finalJS += loadThings(functionsToLoad, 'function', extractFunction, searchJs);
277
278     var loaded = loadContent(finalJS);
279     var index = loaded.buildIndex(searchIndex.rawSearchIndex);
280
281     return [loaded, index];
282 }
283
284 function runSearch(query, expected, index, loaded, loadedFile, queryName) {
285     const filter_crate = loadedFile.FILTER_CRATE;
286     const ignore_order = loadedFile.ignore_order;
287     const exact_check = loadedFile.exact_check;
288
289     var results = loaded.execSearch(loaded.getQuery(query), index, filter_crate);
290     var error_text = [];
291
292     for (var key in expected) {
293         if (!expected.hasOwnProperty(key)) {
294             continue;
295         }
296         if (!results.hasOwnProperty(key)) {
297             error_text.push('==> Unknown key "' + key + '"');
298             break;
299         }
300         var entry = expected[key];
301
302         if (exact_check == true && entry.length !== results[key].length) {
303             error_text.push(queryName + "==> Expected exactly " + entry.length +
304                             " results but found " + results[key].length + " in '" + key + "'");
305         }
306
307         var prev_pos = -1;
308         for (var i = 0; i < entry.length; ++i) {
309             var entry_pos = lookForEntry(entry[i], results[key]);
310             if (entry_pos === null) {
311                 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
312                                 JSON.stringify(entry[i]) + "'");
313                 // By default, we just compare the two first items.
314                 let item_to_diff = 0;
315                 if ((ignore_order === false || exact_check === true) && i < results[key].length) {
316                     item_to_diff = i;
317                 }
318                 error_text.push("Diff of first error:\n" +
319                     betterLookingDiff(entry[i], results[key][item_to_diff]));
320             } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
321                 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
322                                 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
323                                 JSON.stringify(results[key][i]) + "'");
324             } else if (ignore_order === false && entry_pos < prev_pos) {
325                 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
326                                 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
327             } else {
328                 prev_pos = entry_pos;
329             }
330         }
331     }
332     return error_text;
333 }
334
335 function checkResult(error_text, loadedFile, displaySuccess) {
336     if (error_text.length === 0 && loadedFile.should_fail === true) {
337         console.log("FAILED");
338         console.log("==> Test was supposed to fail but all items were found...");
339     } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
340         console.log("FAILED");
341         console.log(error_text.join("\n"));
342     } else {
343         if (displaySuccess) {
344             console.log("OK");
345         }
346         return 0;
347     }
348     return 1;
349 }
350
351 function runChecks(testFile, loaded, index) {
352     var testFileContent = readFile(testFile) + 'exports.QUERY = QUERY;exports.EXPECTED = EXPECTED;';
353     if (testFileContent.indexOf("FILTER_CRATE") !== -1) {
354         testFileContent += "exports.FILTER_CRATE = FILTER_CRATE;";
355     }
356     var loadedFile = loadContent(testFileContent);
357
358     const expected = loadedFile.EXPECTED;
359     const query = loadedFile.QUERY;
360
361     if (Array.isArray(query)) {
362         if (!Array.isArray(expected)) {
363             console.log("FAILED");
364             console.log("==> If QUERY variable is an array, EXPECTED should be an array too");
365             return 1;
366         } else if (query.length !== expected.length) {
367             console.log("FAILED");
368             console.log("==> QUERY variable should have the same length as EXPECTED");
369             return 1;
370         }
371         for (var i = 0; i < query.length; ++i) {
372             var error_text = runSearch(query[i], expected[i], index, loaded, loadedFile,
373                 "[ query `" + query[i] + "`]");
374             if (checkResult(error_text, loadedFile, false) !== 0) {
375                 return 1;
376             }
377         }
378         console.log("OK");
379         return 0;
380     }
381     var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
382     return checkResult(error_text, loadedFile, true);
383 }
384
385 function load_files(doc_folder, resource_suffix, crate) {
386     var searchJs = readFile(path.join(doc_folder, "search" + resource_suffix + ".js"));
387     var storageJs = readFile(path.join(doc_folder, "storage" + resource_suffix + ".js"));
388     var searchIndex = readFile(
389         path.join(doc_folder, "search-index" + resource_suffix + ".js")).split("\n");
390
391     return loadSearchJsAndIndex(searchJs, searchIndex, storageJs, crate);
392 }
393
394 function showHelp() {
395     console.log("rustdoc-js options:");
396     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
397     console.log("  --help                     : show this message then quit");
398     console.log("  --crate-name [STRING]      : crate name to be used");
399     console.log("  --test-file [PATH]         : location of the JS test file");
400     console.log("  --test-folder [PATH]       : location of the JS tests folder");
401     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
402 }
403
404 function parseOptions(args) {
405     var opts = {
406         "crate_name": "",
407         "resource_suffix": "",
408         "doc_folder": "",
409         "test_folder": "",
410         "test_file": "",
411     };
412     var correspondances = {
413         "--resource-suffix": "resource_suffix",
414         "--doc-folder": "doc_folder",
415         "--test-folder": "test_folder",
416         "--test-file": "test_file",
417         "--crate-name": "crate_name",
418     };
419
420     for (var i = 0; i < args.length; ++i) {
421         if (args[i] === "--resource-suffix"
422             || args[i] === "--doc-folder"
423             || args[i] === "--test-folder"
424             || args[i] === "--test-file"
425             || args[i] === "--crate-name") {
426             i += 1;
427             if (i >= args.length) {
428                 console.log("Missing argument after `" + args[i - 1] + "` option.");
429                 return null;
430             }
431             opts[correspondances[args[i - 1]]] = args[i];
432         } else if (args[i] === "--help") {
433             showHelp();
434             process.exit(0);
435         } else {
436             console.log("Unknown option `" + args[i] + "`.");
437             console.log("Use `--help` to see the list of options");
438             return null;
439         }
440     }
441     if (opts["doc_folder"].length < 1) {
442         console.log("Missing `--doc-folder` option.");
443     } else if (opts["crate_name"].length < 1) {
444         console.log("Missing `--crate-name` option.");
445     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
446         console.log("At least one of `--test-folder` or `--test-file` option is required.");
447     } else {
448         return opts;
449     }
450     return null;
451 }
452
453 function checkFile(test_file, opts, loaded, index) {
454     const test_name = path.basename(test_file, ".js");
455
456     process.stdout.write('Checking "' + test_name + '" ... ');
457     return runChecks(test_file, loaded, index);
458 }
459
460 function main(argv) {
461     var opts = parseOptions(argv.slice(2));
462     if (opts === null) {
463         return 1;
464     }
465
466     var [loaded, index] = load_files(
467         opts["doc_folder"],
468         opts["resource_suffix"],
469         opts["crate_name"]);
470     var errors = 0;
471
472     if (opts["test_file"].length !== 0) {
473         errors += checkFile(opts["test_file"], opts, loaded, index);
474     }
475     if (opts["test_folder"].length !== 0) {
476         fs.readdirSync(opts["test_folder"]).forEach(function(file) {
477             if (!file.endsWith(".js")) {
478                 return;
479             }
480             errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
481         });
482     }
483     return errors > 0 ? 1 : 0;
484 }
485
486 process.exit(main(process.argv));