]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
Rollup merge of #72818 - GuillaumeGomez:cleanup-e0622, r=Dylan-DPC
[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 lookForEntry(entry, data) {
194     for (var i = 0; i < data.length; ++i) {
195         var allGood = true;
196         for (var key in entry) {
197             if (!entry.hasOwnProperty(key)) {
198                 continue;
199             }
200             var value = data[i][key];
201             // To make our life easier, if there is a "parent" type, we add it to the path.
202             if (key === 'path' && data[i]['parent'] !== undefined) {
203                 if (value.length > 0) {
204                     value += '::' + data[i]['parent']['name'];
205                 } else {
206                     value = data[i]['parent']['name'];
207                 }
208             }
209             if (value !== entry[key]) {
210                 allGood = false;
211                 break;
212             }
213         }
214         if (allGood === true) {
215             return i;
216         }
217     }
218     return null;
219 }
220
221 function loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate) {
222     if (searchIndex[searchIndex.length - 1].length === 0) {
223         searchIndex.pop();
224     }
225     searchIndex.pop();
226     var fullSearchIndex = searchIndex.join("\n") + '\nexports.rawSearchIndex = searchIndex;';
227     searchIndex = loadContent(fullSearchIndex);
228     var finalJS = "";
229
230     var arraysToLoad = ["itemTypes"];
231     var variablesToLoad = ["MAX_LEV_DISTANCE", "MAX_RESULTS", "NO_TYPE_FILTER",
232                            "GENERICS_DATA", "NAME", "INPUTS_DATA", "OUTPUT_DATA",
233                            "TY_PRIMITIVE", "TY_KEYWORD",
234                            "levenshtein_row2"];
235     // execQuery first parameter is built in getQuery (which takes in the search input).
236     // execQuery last parameter is built in buildIndex.
237     // buildIndex requires the hashmap from search-index.
238     var functionsToLoad = ["buildHrefAndPath", "pathSplitter", "levenshtein", "validateResult",
239                            "handleAliases", "getQuery", "buildIndex", "execQuery", "execSearch"];
240
241     ALIASES = {};
242     finalJS += 'window = { "currentCrate": "' + crate + '" };\n';
243     finalJS += 'var rootPath = "../";\n';
244     finalJS += loadThings(["hasOwnProperty", "onEach"], 'function', extractFunction, storageJs);
245     finalJS += loadThings(arraysToLoad, 'array', extractArrayVariable, mainJs);
246     finalJS += loadThings(variablesToLoad, 'variable', extractVariable, mainJs);
247     finalJS += loadThings(functionsToLoad, 'function', extractFunction, mainJs);
248
249     var loaded = loadContent(finalJS);
250     var index = loaded.buildIndex(searchIndex.rawSearchIndex);
251
252     return [loaded, index];
253 }
254
255 function runSearch(query, expected, index, loaded, loadedFile, queryName) {
256     const filter_crate = loadedFile.FILTER_CRATE;
257     const ignore_order = loadedFile.ignore_order;
258     const exact_check = loadedFile.exact_check;
259
260     var results = loaded.execSearch(loaded.getQuery(query), index, filter_crate);
261     var error_text = [];
262
263     for (var key in expected) {
264         if (!expected.hasOwnProperty(key)) {
265             continue;
266         }
267         if (!results.hasOwnProperty(key)) {
268             error_text.push('==> Unknown key "' + key + '"');
269             break;
270         }
271         var entry = expected[key];
272         var prev_pos = -1;
273         for (var i = 0; i < entry.length; ++i) {
274             var entry_pos = lookForEntry(entry[i], results[key]);
275             if (entry_pos === null) {
276                 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
277                                 JSON.stringify(entry[i]) + "'");
278             } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
279                 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
280                                 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
281                                 JSON.stringify(results[key][i]) + "'");
282             } else if (ignore_order === false && entry_pos < prev_pos) {
283                 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
284                                 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
285             } else {
286                 prev_pos = entry_pos;
287             }
288         }
289     }
290     return error_text;
291 }
292
293 function checkResult(error_text, loadedFile, displaySuccess) {
294     if (error_text.length === 0 && loadedFile.should_fail === true) {
295         console.log("FAILED");
296         console.log("==> Test was supposed to fail but all items were found...");
297     } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
298         console.log("FAILED");
299         console.log(error_text.join("\n"));
300     } else {
301         if (displaySuccess) {
302             console.log("OK");
303         }
304         return 0;
305     }
306     return 1;
307 }
308
309 function runChecks(testFile, loaded, index) {
310     var loadedFile = loadContent(
311         readFile(testFile) + 'exports.QUERY = QUERY;exports.EXPECTED = EXPECTED;');
312
313     const expected = loadedFile.EXPECTED;
314     const query = loadedFile.QUERY;
315
316     if (Array.isArray(query)) {
317         if (!Array.isArray(expected)) {
318             console.log("FAILED");
319             console.log("==> If QUERY variable is an array, EXPECTED should be an array too");
320             return 1;
321         } else if (query.length !== expected.length) {
322             console.log("FAILED");
323             console.log("==> QUERY variable should have the same length as EXPECTED");
324             return 1;
325         }
326         for (var i = 0; i < query.length; ++i) {
327             var error_text = runSearch(query[i], expected[i], index, loaded, loadedFile,
328                 "[ query `" + query[i] + "`]");
329             if (checkResult(error_text, loadedFile, false) !== 0) {
330                 return 1;
331             }
332         }
333         console.log("OK");
334         return 0;
335     }
336     var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
337     return checkResult(error_text, loadedFile, true);
338 }
339
340 function load_files(doc_folder, resource_suffix, crate) {
341     var mainJs = readFile(path.join(doc_folder, "main" + resource_suffix + ".js"));
342     var storageJs = readFile(path.join(doc_folder, "storage" + resource_suffix + ".js"));
343     var searchIndex = readFile(
344         path.join(doc_folder, "search-index" + resource_suffix + ".js")).split("\n");
345
346     return loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate);
347 }
348
349 function showHelp() {
350     console.log("rustdoc-js options:");
351     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
352     console.log("  --help                     : show this message then quit");
353     console.log("  --crate-name [STRING]      : crate name to be used");
354     console.log("  --test-file [PATH]         : location of the JS test file");
355     console.log("  --test-folder [PATH]       : location of the JS tests folder");
356     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
357 }
358
359 function parseOptions(args) {
360     var opts = {
361         "crate_name": "",
362         "resource_suffix": "",
363         "doc_folder": "",
364         "test_folder": "",
365         "test_file": "",
366     };
367     var correspondances = {
368         "--resource-suffix": "resource_suffix",
369         "--doc-folder": "doc_folder",
370         "--test-folder": "test_folder",
371         "--test-file": "test_file",
372         "--crate-name": "crate_name",
373     };
374
375     for (var i = 0; i < args.length; ++i) {
376         if (args[i] === "--resource-suffix"
377             || args[i] === "--doc-folder"
378             || args[i] === "--test-folder"
379             || args[i] === "--test-file"
380             || args[i] === "--crate-name") {
381             i += 1;
382             if (i >= args.length) {
383                 console.log("Missing argument after `" + args[i - 1] + "` option.");
384                 return null;
385             }
386             opts[correspondances[args[i - 1]]] = args[i];
387         } else if (args[i] === "--help") {
388             showHelp();
389             process.exit(0);
390         } else {
391             console.log("Unknown option `" + args[i] + "`.");
392             console.log("Use `--help` to see the list of options");
393             return null;
394         }
395     }
396     if (opts["doc_folder"].length < 1) {
397         console.log("Missing `--doc-folder` option.");
398     } else if (opts["crate_name"].length < 1) {
399         console.log("Missing `--crate-name` option.");
400     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
401         console.log("At least one of `--test-folder` or `--test-file` option is required.");
402     } else {
403         return opts;
404     }
405     return null;
406 }
407
408 function checkFile(test_file, opts, loaded, index) {
409     const test_name = path.basename(test_file, ".js");
410
411     process.stdout.write('Checking "' + test_name + '" ... ');
412     return runChecks(test_file, loaded, index);
413 }
414
415 function main(argv) {
416     var opts = parseOptions(argv.slice(2));
417     if (opts === null) {
418         return 1;
419     }
420
421     var [loaded, index] = load_files(
422         opts["doc_folder"],
423         opts["resource_suffix"],
424         opts["crate_name"]);
425     var errors = 0;
426
427     if (opts["test_file"].length !== 0) {
428         errors += checkFile(opts["test_file"], opts, loaded, index);
429     }
430     if (opts["test_folder"].length !== 0) {
431         fs.readdirSync(opts["test_folder"]).forEach(function(file) {
432             if (!file.endsWith(".js")) {
433                 return;
434             }
435             errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
436         });
437     }
438     return errors > 0 ? 1 : 0;
439 }
440
441 process.exit(main(process.argv));