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