]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
Auto merge of #91101 - birkenfeld:io_error_docs, 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 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     }
361     var loadedFile = loadContent(testFileContent);
362
363     const expected = loadedFile.EXPECTED;
364     const query = loadedFile.QUERY;
365
366     if (Array.isArray(query)) {
367         if (!Array.isArray(expected)) {
368             console.log("FAILED");
369             console.log("==> If QUERY variable is an array, EXPECTED should be an array too");
370             return 1;
371         } else if (query.length !== expected.length) {
372             console.log("FAILED");
373             console.log("==> QUERY variable should have the same length as EXPECTED");
374             return 1;
375         }
376         for (var i = 0; i < query.length; ++i) {
377             var error_text = runSearch(query[i], expected[i], index, loaded, loadedFile,
378                 "[ query `" + query[i] + "`]");
379             if (checkResult(error_text, loadedFile, false) !== 0) {
380                 return 1;
381             }
382         }
383         console.log("OK");
384         return 0;
385     }
386     var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
387     return checkResult(error_text, loadedFile, true);
388 }
389
390 function load_files(doc_folder, resource_suffix, crate) {
391     var searchJs = readFile(path.join(doc_folder, "search" + resource_suffix + ".js"));
392     var storageJs = readFile(path.join(doc_folder, "storage" + resource_suffix + ".js"));
393     var searchIndex = readFile(
394         path.join(doc_folder, "search-index" + resource_suffix + ".js")).split("\n");
395
396     return loadSearchJsAndIndex(searchJs, searchIndex, storageJs, crate);
397 }
398
399 function showHelp() {
400     console.log("rustdoc-js options:");
401     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
402     console.log("  --help                     : show this message then quit");
403     console.log("  --crate-name [STRING]      : crate name to be used");
404     console.log("  --test-file [PATHs]        : location of the JS test files (can be called " +
405                 "multiple times)");
406     console.log("  --test-folder [PATH]       : location of the JS tests folder");
407     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
408 }
409
410 function parseOptions(args) {
411     var opts = {
412         "crate_name": "",
413         "resource_suffix": "",
414         "doc_folder": "",
415         "test_folder": "",
416         "test_file": [],
417     };
418     var correspondences = {
419         "--resource-suffix": "resource_suffix",
420         "--doc-folder": "doc_folder",
421         "--test-folder": "test_folder",
422         "--test-file": "test_file",
423         "--crate-name": "crate_name",
424     };
425
426     for (var i = 0; i < args.length; ++i) {
427         if (correspondences.hasOwnProperty(args[i])) {
428             i += 1;
429             if (i >= args.length) {
430                 console.log("Missing argument after `" + args[i - 1] + "` option.");
431                 return null;
432             }
433             if (args[i - 1] !== "--test-file") {
434                 opts[correspondences[args[i - 1]]] = args[i];
435             } else {
436                 opts[correspondences[args[i - 1]]].push(args[i]);
437             }
438         } else if (args[i] === "--help") {
439             showHelp();
440             process.exit(0);
441         } else {
442             console.log("Unknown option `" + args[i] + "`.");
443             console.log("Use `--help` to see the list of options");
444             return null;
445         }
446     }
447     if (opts["doc_folder"].length < 1) {
448         console.log("Missing `--doc-folder` option.");
449     } else if (opts["crate_name"].length < 1) {
450         console.log("Missing `--crate-name` option.");
451     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
452         console.log("At least one of `--test-folder` or `--test-file` option is required.");
453     } else {
454         return opts;
455     }
456     return null;
457 }
458
459 function checkFile(test_file, opts, loaded, index) {
460     const test_name = path.basename(test_file, ".js");
461
462     process.stdout.write('Checking "' + test_name + '" ... ');
463     return runChecks(test_file, loaded, index);
464 }
465
466 function main(argv) {
467     var opts = parseOptions(argv.slice(2));
468     if (opts === null) {
469         return 1;
470     }
471
472     var [loaded, index] = load_files(
473         opts["doc_folder"],
474         opts["resource_suffix"],
475         opts["crate_name"]);
476     var errors = 0;
477
478     if (opts["test_file"].length !== 0) {
479         opts["test_file"].forEach(function(file) {
480             errors += checkFile(file, opts, loaded, index);
481         });
482     } else if (opts["test_folder"].length !== 0) {
483         fs.readdirSync(opts["test_folder"]).forEach(function(file) {
484             if (!file.endsWith(".js")) {
485                 return;
486             }
487             errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
488         });
489     }
490     return errors > 0 ? 1 : 0;
491 }
492
493 process.exit(main(process.argv));