]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
Improve include macro documentation
[rust.git] / src / tools / rustdoc-js / tester.js
1 const fs = require('fs');
2 const path = require('path');
3
4 function loadContent(content) {
5     var Module = module.constructor;
6     var m = new Module();
7     m._compile(content, "tmp.js");
8     m.exports.ignore_order = content.indexOf("\n// ignore-order\n") !== -1 ||
9         content.startsWith("// ignore-order\n");
10     m.exports.exact_check = content.indexOf("\n// exact-check\n") !== -1 ||
11         content.startsWith("// exact-check\n");
12     m.exports.should_fail = content.indexOf("\n// should-fail\n") !== -1 ||
13         content.startsWith("// should-fail\n");
14     return m.exports;
15 }
16
17 function readFile(filePath) {
18     return fs.readFileSync(filePath, 'utf8');
19 }
20
21 function contentToDiffLine(key, value) {
22     return `"${key}": "${value}",`;
23 }
24
25 // This function is only called when no matching result was found and therefore will only display
26 // the diff between the two items.
27 function betterLookingDiff(entry, data) {
28     let output = ' {\n';
29     let spaces = '     ';
30     for (let key in entry) {
31         if (!entry.hasOwnProperty(key)) {
32             continue;
33         }
34         if (!data || !data.hasOwnProperty(key)) {
35             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
36             continue;
37         }
38         let value = data[key];
39         if (value !== entry[key]) {
40             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
41             output += '+' + spaces + contentToDiffLine(key, value) + '\n';
42         } else {
43             output += spaces + contentToDiffLine(key, value) + '\n';
44         }
45     }
46     return output + ' }';
47 }
48
49 function lookForEntry(entry, data) {
50     for (var i = 0; i < data.length; ++i) {
51         var allGood = true;
52         for (var key in entry) {
53             if (!entry.hasOwnProperty(key)) {
54                 continue;
55             }
56             var value = data[i][key];
57             // To make our life easier, if there is a "parent" type, we add it to the path.
58             if (key === 'path' && data[i]['parent'] !== undefined) {
59                 if (value.length > 0) {
60                     value += '::' + data[i]['parent']['name'];
61                 } else {
62                     value = data[i]['parent']['name'];
63                 }
64             }
65             if (value !== entry[key]) {
66                 allGood = false;
67                 break;
68             }
69         }
70         if (allGood === true) {
71             return i;
72         }
73     }
74     return null;
75 }
76
77 // This function checks if `expected` has all the required fields needed for the checks.
78 function checkNeededFields(fullPath, expected, error_text, queryName, position) {
79     let fieldsToCheck;
80     if (fullPath.length === 0) {
81         fieldsToCheck = [
82             "foundElems",
83             "original",
84             "returned",
85             "typeFilter",
86             "userQuery",
87             "error",
88         ];
89     } else if (fullPath.endsWith("elems") || fullPath.endsWith("generics")) {
90         fieldsToCheck = [
91             "name",
92             "fullPath",
93             "pathWithoutLast",
94             "pathLast",
95             "generics",
96         ];
97     } else {
98         fieldsToCheck = [];
99     }
100     for (var i = 0; i < fieldsToCheck.length; ++i) {
101         const field = fieldsToCheck[i];
102         if (!expected.hasOwnProperty(field)) {
103             let text = `${queryName}==> Mandatory key \`${field}\` is not present`;
104             if (fullPath.length > 0) {
105                 text += ` in field \`${fullPath}\``;
106                 if (position != null) {
107                     text += ` (position ${position})`;
108                 }
109             }
110             error_text.push(text);
111         }
112     }
113 }
114
115 function valueCheck(fullPath, expected, result, error_text, queryName) {
116     if (Array.isArray(expected)) {
117         for (var i = 0; i < expected.length; ++i) {
118             checkNeededFields(fullPath, expected[i], error_text, queryName, i);
119             if (i >= result.length) {
120                 error_text.push(`${queryName}==> EXPECTED has extra value in array from field ` +
121                     `\`${fullPath}\` (position ${i}): \`${JSON.stringify(expected[i])}\``);
122             } else {
123                 valueCheck(fullPath + '[' + i + ']', expected[i], result[i], error_text, queryName);
124             }
125         }
126         for (; i < result.length; ++i) {
127             error_text.push(`${queryName}==> RESULT has extra value in array from field ` +
128                 `\`${fullPath}\` (position ${i}): \`${JSON.stringify(result[i])}\` ` +
129                 'compared to EXPECTED');
130         }
131     } else if (expected !== null && typeof expected !== "undefined" &&
132                expected.constructor == Object) {
133         for (const key in expected) {
134             if (!expected.hasOwnProperty(key)) {
135                 continue;
136             }
137             if (!result.hasOwnProperty(key)) {
138                 error_text.push('==> Unknown key "' + key + '"');
139                 break;
140             }
141             const obj_path = fullPath + (fullPath.length > 0 ? '.' : '') + key;
142             valueCheck(obj_path, expected[key], result[key], error_text, queryName);
143         }
144     } else {
145         expectedValue = JSON.stringify(expected);
146         resultValue = JSON.stringify(result);
147         if (expectedValue != resultValue) {
148             error_text.push(`${queryName}==> Different values for field \`${fullPath}\`:\n` +
149                 `EXPECTED: \`${expectedValue}\`\nRESULT:   \`${resultValue}\``);
150         }
151     }
152 }
153
154 function runParser(query, expected, parseQuery, queryName) {
155     var error_text = [];
156     checkNeededFields("", expected, error_text, queryName, null);
157     if (error_text.length === 0) {
158         valueCheck('', expected, parseQuery(query), error_text, queryName);
159     }
160     return error_text;
161 }
162
163 function runSearch(query, expected, doSearch, loadedFile, queryName) {
164     const ignore_order = loadedFile.ignore_order;
165     const exact_check = loadedFile.exact_check;
166
167     var results = doSearch(query, loadedFile.FILTER_CRATE);
168     var error_text = [];
169
170     for (var key in expected) {
171         if (!expected.hasOwnProperty(key)) {
172             continue;
173         }
174         if (!results.hasOwnProperty(key)) {
175             error_text.push('==> Unknown key "' + key + '"');
176             break;
177         }
178         var entry = expected[key];
179
180         if (exact_check == true && entry.length !== results[key].length) {
181             error_text.push(queryName + "==> Expected exactly " + entry.length +
182                             " results but found " + results[key].length + " in '" + key + "'");
183         }
184
185         var prev_pos = -1;
186         for (var i = 0; i < entry.length; ++i) {
187             var entry_pos = lookForEntry(entry[i], results[key]);
188             if (entry_pos === null) {
189                 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
190                                 JSON.stringify(entry[i]) + "'");
191                 // By default, we just compare the two first items.
192                 let item_to_diff = 0;
193                 if ((ignore_order === false || exact_check === true) && i < results[key].length) {
194                     item_to_diff = i;
195                 }
196                 error_text.push("Diff of first error:\n" +
197                     betterLookingDiff(entry[i], results[key][item_to_diff]));
198             } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
199                 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
200                                 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
201                                 JSON.stringify(results[key][i]) + "'");
202             } else if (ignore_order === false && entry_pos < prev_pos) {
203                 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
204                                 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
205             } else {
206                 prev_pos = entry_pos;
207             }
208         }
209     }
210     return error_text;
211 }
212
213 function checkResult(error_text, loadedFile, displaySuccess) {
214     if (error_text.length === 0 && loadedFile.should_fail === true) {
215         console.log("FAILED");
216         console.log("==> Test was supposed to fail but all items were found...");
217     } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
218         console.log("FAILED");
219         console.log(error_text.join("\n"));
220     } else {
221         if (displaySuccess) {
222             console.log("OK");
223         }
224         return 0;
225     }
226     return 1;
227 }
228
229 function runCheck(loadedFile, key, callback) {
230     const expected = loadedFile[key];
231     const query = loadedFile.QUERY;
232
233     if (Array.isArray(query)) {
234         if (!Array.isArray(expected)) {
235             console.log("FAILED");
236             console.log(`==> If QUERY variable is an array, ${key} should be an array too`);
237             return 1;
238         } else if (query.length !== expected.length) {
239             console.log("FAILED");
240             console.log(`==> QUERY variable should have the same length as ${key}`);
241             return 1;
242         }
243         for (var i = 0; i < query.length; ++i) {
244             var error_text = callback(query[i], expected[i], "[ query `" + query[i] + "`]");
245             if (checkResult(error_text, loadedFile, false) !== 0) {
246                 return 1;
247             }
248         }
249         console.log("OK");
250     } else {
251         var error_text = callback(query, expected, "");
252         if (checkResult(error_text, loadedFile, true) !== 0) {
253             return 1;
254         }
255     }
256     return 0;
257 }
258
259 function runChecks(testFile, doSearch, parseQuery) {
260     var checkExpected = false;
261     var checkParsed = false;
262     var testFileContent = readFile(testFile) + 'exports.QUERY = QUERY;';
263
264     if (testFileContent.indexOf("FILTER_CRATE") !== -1) {
265         testFileContent += "exports.FILTER_CRATE = FILTER_CRATE;";
266     } else {
267         testFileContent += "exports.FILTER_CRATE = null;";
268     }
269
270     if (testFileContent.indexOf("\nconst EXPECTED") !== -1) {
271         testFileContent += 'exports.EXPECTED = EXPECTED;';
272         checkExpected = true;
273     }
274     if (testFileContent.indexOf("\nconst PARSED") !== -1) {
275         testFileContent += 'exports.PARSED = PARSED;';
276         checkParsed = true;
277     }
278     if (!checkParsed && !checkExpected) {
279         console.log("FAILED");
280         console.log("==> At least `PARSED` or `EXPECTED` is needed!");
281         return 1;
282     }
283
284     const loadedFile = loadContent(testFileContent);
285     var res = 0;
286
287     if (checkExpected) {
288         res += runCheck(loadedFile, "EXPECTED", (query, expected, text) => {
289             return runSearch(query, expected, doSearch, loadedFile, text);
290         });
291     }
292     if (checkParsed) {
293         res += runCheck(loadedFile, "PARSED", (query, expected, text) => {
294             return runParser(query, expected, parseQuery, text);
295         });
296     }
297     return res;
298 }
299
300 /**
301  * Load searchNNN.js and search-indexNNN.js.
302  *
303  * @param {string} doc_folder      - Path to a folder generated by running rustdoc
304  * @param {string} resource_suffix - Version number between filename and .js, e.g. "1.59.0"
305  * @returns {Object}               - Object containing two keys: `doSearch`, which runs a search
306  *   with the loaded index and returns a table of results; and `parseQuery`, which is the
307  *   `parseQuery` function exported from the search module.
308  */
309 function loadSearchJS(doc_folder, resource_suffix) {
310     const searchIndexJs = path.join(doc_folder, "search-index" + resource_suffix + ".js");
311     const searchIndex = require(searchIndexJs);
312
313     const staticFiles = path.join(doc_folder, "static.files");
314     const searchJs = fs.readdirSync(staticFiles).find(
315         f => f.match(/search.*\.js$/));
316     const searchModule = require(path.join(staticFiles, searchJs));
317     const searchWords = searchModule.initSearch(searchIndex.searchIndex);
318
319     return {
320         doSearch: function (queryStr, filterCrate, currentCrate) {
321             return searchModule.execQuery(searchModule.parseQuery(queryStr), searchWords,
322                 filterCrate, currentCrate);
323         },
324         parseQuery: searchModule.parseQuery,
325     }
326 }
327
328 function showHelp() {
329     console.log("rustdoc-js options:");
330     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
331     console.log("  --help                     : show this message then quit");
332     console.log("  --crate-name [STRING]      : crate name to be used");
333     console.log("  --test-file [PATHs]        : location of the JS test files (can be called " +
334                 "multiple times)");
335     console.log("  --test-folder [PATH]       : location of the JS tests folder");
336     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
337 }
338
339 function parseOptions(args) {
340     var opts = {
341         "crate_name": "",
342         "resource_suffix": "",
343         "doc_folder": "",
344         "test_folder": "",
345         "test_file": [],
346     };
347     var correspondences = {
348         "--resource-suffix": "resource_suffix",
349         "--doc-folder": "doc_folder",
350         "--test-folder": "test_folder",
351         "--test-file": "test_file",
352         "--crate-name": "crate_name",
353     };
354
355     for (var i = 0; i < args.length; ++i) {
356         if (correspondences.hasOwnProperty(args[i])) {
357             i += 1;
358             if (i >= args.length) {
359                 console.log("Missing argument after `" + args[i - 1] + "` option.");
360                 return null;
361             }
362             if (args[i - 1] !== "--test-file") {
363                 opts[correspondences[args[i - 1]]] = args[i];
364             } else {
365                 opts[correspondences[args[i - 1]]].push(args[i]);
366             }
367         } else if (args[i] === "--help") {
368             showHelp();
369             process.exit(0);
370         } else {
371             console.log("Unknown option `" + args[i] + "`.");
372             console.log("Use `--help` to see the list of options");
373             return null;
374         }
375     }
376     if (opts["doc_folder"].length < 1) {
377         console.log("Missing `--doc-folder` option.");
378     } else if (opts["crate_name"].length < 1) {
379         console.log("Missing `--crate-name` option.");
380     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
381         console.log("At least one of `--test-folder` or `--test-file` option is required.");
382     } else {
383         return opts;
384     }
385     return null;
386 }
387
388 function main(argv) {
389     var opts = parseOptions(argv.slice(2));
390     if (opts === null) {
391         return 1;
392     }
393
394     let parseAndSearch = loadSearchJS(
395         opts["doc_folder"],
396         opts["resource_suffix"]);
397     var errors = 0;
398
399     let doSearch = function (queryStr, filterCrate) {
400         return parseAndSearch.doSearch(queryStr, filterCrate, opts["crate_name"]);
401     };
402
403     if (opts["test_file"].length !== 0) {
404         opts["test_file"].forEach(function (file) {
405             process.stdout.write(`Testing ${file} ... `);
406             errors += runChecks(file, doSearch, parseAndSearch.parseQuery);
407         });
408     } else if (opts["test_folder"].length !== 0) {
409         fs.readdirSync(opts["test_folder"]).forEach(function (file) {
410             if (!file.endsWith(".js")) {
411                 return;
412             }
413             process.stdout.write(`Testing ${file} ... `);
414             errors += runChecks(path.join(opts["test_folder"], file), doSearch,
415                     parseAndSearch.parseQuery);
416         });
417     }
418     return errors > 0 ? 1 : 0;
419 }
420
421 process.exit(main(process.argv));