1 const fs = require('fs');
2 const path = require('path');
4 function getNextStep(content, pos, stop) {
5 while (pos < content.length && content[pos] !== stop &&
6 (content[pos] === ' ' || content[pos] === '\t' || content[pos] === '\n')) {
9 if (pos >= content.length) {
12 if (content[pos] !== stop) {
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
22 function extractFunction(content, functionName) {
24 var splitter = "function " + functionName + "(";
27 var start = content.indexOf(splitter);
32 while (pos < content.length && content[pos] !== ')') {
35 if (pos >= content.length) {
38 pos = getNextStep(content, pos + 1, '{');
42 content = content.slice(-pos);
45 while (pos < content.length) {
46 // Eat single-line comments
47 if (content[pos] === '/' && pos > 0 && content[pos-1] === '/') {
50 } while (pos < content.length && content[pos] !== '\n');
53 } else if (content[pos] === '"' || content[pos] === "'" || content[pos] === "`") {
54 var stop = content[pos];
55 var is_escaped = false;
57 if (content[pos] === '\\') {
62 } while (pos < content.length &&
63 (content[pos] !== stop || content[pos - 1] === '\\'));
65 // Otherwise, check for indent
66 } else if (content[pos] === '{') {
68 } else if (content[pos] === '}') {
71 return content.slice(start, pos + 1);
76 content = content.slice(start + 1);
81 // Stupid function extractor for array.
82 function extractArrayVariable(content, arrayName) {
83 var splitter = "var " + arrayName;
85 var start = content.indexOf(splitter);
89 var pos = getNextStep(content, start, '=');
93 content = content.slice(-pos);
96 pos = getNextStep(content, pos, '[');
100 content = content.slice(-pos);
103 while (pos < content.length) {
104 if (content[pos] === '"' || content[pos] === "'") {
105 var stop = content[pos];
107 if (content[pos] === '\\') {
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);
121 content = content.slice(start + 1);
126 // Stupid function extractor for variable.
127 function extractVariable(content, varName) {
128 var splitter = "var " + varName;
130 var start = content.indexOf(splitter);
134 var pos = getNextStep(content, start, '=');
137 } else if (pos < 0) {
138 content = content.slice(-pos);
141 while (pos < content.length) {
142 if (content[pos] === '"' || content[pos] === "'") {
143 var stop = content[pos];
145 if (content[pos] === '\\') {
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);
157 content = content.slice(start + 1);
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");
175 function readFile(filePath) {
176 return fs.readFileSync(filePath, 'utf8');
179 function loadThings(thingsToLoad, kindOfLoad, funcToCall, fileContent) {
181 for (var i = 0; i < thingsToLoad.length; ++i) {
182 var tmp = funcToCall(fileContent, thingsToLoad[i]);
184 console.log('unable to find ' + kindOfLoad + ' "' + thingsToLoad[i] + '"');
188 content += 'exports.' + thingsToLoad[i] + ' = ' + thingsToLoad[i] + ';';
193 function contentToDiffLine(key, value) {
194 return `"${key}": "${value}",`;
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) {
202 for (let key in entry) {
203 if (!entry.hasOwnProperty(key)) {
206 if (!data || !data.hasOwnProperty(key)) {
207 output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
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';
215 output += spaces + contentToDiffLine(key, value) + '\n';
218 return output + ' }';
221 function lookForEntry(entry, data) {
222 for (var i = 0; i < data.length; ++i) {
224 for (var key in entry) {
225 if (!entry.hasOwnProperty(key)) {
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'];
234 value = data[i]['parent']['name'];
237 if (value !== entry[key]) {
242 if (allGood === true) {
249 function loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate) {
250 if (searchIndex[searchIndex.length - 1].length === 0) {
254 var fullSearchIndex = searchIndex.join("\n") + '\nexports.rawSearchIndex = searchIndex;';
255 searchIndex = loadContent(fullSearchIndex);
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",
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"];
270 finalJS += 'window = { "currentCrate": "' + crate + '", rootPath: "../" };\n';
271 finalJS += loadThings(["hasOwnProperty", "onEach"], 'function', extractFunction, storageJs);
272 finalJS += loadThings(arraysToLoad, 'array', extractArrayVariable, mainJs);
273 finalJS += loadThings(variablesToLoad, 'variable', extractVariable, mainJs);
274 finalJS += loadThings(functionsToLoad, 'function', extractFunction, mainJs);
276 var loaded = loadContent(finalJS);
277 var index = loaded.buildIndex(searchIndex.rawSearchIndex);
279 return [loaded, index];
282 function runSearch(query, expected, index, loaded, loadedFile, queryName) {
283 const filter_crate = loadedFile.FILTER_CRATE;
284 const ignore_order = loadedFile.ignore_order;
285 const exact_check = loadedFile.exact_check;
287 var results = loaded.execSearch(loaded.getQuery(query), index, filter_crate);
290 for (var key in expected) {
291 if (!expected.hasOwnProperty(key)) {
294 if (!results.hasOwnProperty(key)) {
295 error_text.push('==> Unknown key "' + key + '"');
298 var entry = expected[key];
300 if (exact_check == true && entry.length !== results[key].length) {
301 error_text.push(queryName + "==> Expected exactly " + entry.length +
302 " results but found " + results[key].length + " in '" + key + "'");
306 for (var i = 0; i < entry.length; ++i) {
307 var entry_pos = lookForEntry(entry[i], results[key]);
308 if (entry_pos === null) {
309 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
310 JSON.stringify(entry[i]) + "'");
311 // By default, we just compare the two first items.
312 let item_to_diff = 0;
313 if ((ignore_order === false || exact_check === true) && i < results[key].length) {
316 error_text.push("Diff of first error:\n" +
317 betterLookingDiff(entry[i], results[key][item_to_diff]));
318 } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
319 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
320 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
321 JSON.stringify(results[key][i]) + "'");
322 } else if (ignore_order === false && entry_pos < prev_pos) {
323 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
324 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
326 prev_pos = entry_pos;
333 function checkResult(error_text, loadedFile, displaySuccess) {
334 if (error_text.length === 0 && loadedFile.should_fail === true) {
335 console.log("FAILED");
336 console.log("==> Test was supposed to fail but all items were found...");
337 } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
338 console.log("FAILED");
339 console.log(error_text.join("\n"));
341 if (displaySuccess) {
349 function runChecks(testFile, loaded, index) {
350 var testFileContent = readFile(testFile) + 'exports.QUERY = QUERY;exports.EXPECTED = EXPECTED;';
351 if (testFileContent.indexOf("FILTER_CRATE") !== -1) {
352 testFileContent += "exports.FILTER_CRATE = FILTER_CRATE;";
354 var loadedFile = loadContent(testFileContent);
356 const expected = loadedFile.EXPECTED;
357 const query = loadedFile.QUERY;
359 if (Array.isArray(query)) {
360 if (!Array.isArray(expected)) {
361 console.log("FAILED");
362 console.log("==> If QUERY variable is an array, EXPECTED should be an array too");
364 } else if (query.length !== expected.length) {
365 console.log("FAILED");
366 console.log("==> QUERY variable should have the same length as EXPECTED");
369 for (var i = 0; i < query.length; ++i) {
370 var error_text = runSearch(query[i], expected[i], index, loaded, loadedFile,
371 "[ query `" + query[i] + "`]");
372 if (checkResult(error_text, loadedFile, false) !== 0) {
379 var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
380 return checkResult(error_text, loadedFile, true);
383 function load_files(doc_folder, resource_suffix, crate) {
384 var mainJs = readFile(path.join(doc_folder, "main" + resource_suffix + ".js"));
385 var storageJs = readFile(path.join(doc_folder, "storage" + resource_suffix + ".js"));
386 var searchIndex = readFile(
387 path.join(doc_folder, "search-index" + resource_suffix + ".js")).split("\n");
389 return loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate);
392 function showHelp() {
393 console.log("rustdoc-js options:");
394 console.log(" --doc-folder [PATH] : location of the generated doc folder");
395 console.log(" --help : show this message then quit");
396 console.log(" --crate-name [STRING] : crate name to be used");
397 console.log(" --test-file [PATH] : location of the JS test file");
398 console.log(" --test-folder [PATH] : location of the JS tests folder");
399 console.log(" --resource-suffix [STRING] : suffix to refer to the correct files");
402 function parseOptions(args) {
405 "resource_suffix": "",
410 var correspondances = {
411 "--resource-suffix": "resource_suffix",
412 "--doc-folder": "doc_folder",
413 "--test-folder": "test_folder",
414 "--test-file": "test_file",
415 "--crate-name": "crate_name",
418 for (var i = 0; i < args.length; ++i) {
419 if (args[i] === "--resource-suffix"
420 || args[i] === "--doc-folder"
421 || args[i] === "--test-folder"
422 || args[i] === "--test-file"
423 || args[i] === "--crate-name") {
425 if (i >= args.length) {
426 console.log("Missing argument after `" + args[i - 1] + "` option.");
429 opts[correspondances[args[i - 1]]] = args[i];
430 } else if (args[i] === "--help") {
434 console.log("Unknown option `" + args[i] + "`.");
435 console.log("Use `--help` to see the list of options");
439 if (opts["doc_folder"].length < 1) {
440 console.log("Missing `--doc-folder` option.");
441 } else if (opts["crate_name"].length < 1) {
442 console.log("Missing `--crate-name` option.");
443 } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
444 console.log("At least one of `--test-folder` or `--test-file` option is required.");
451 function checkFile(test_file, opts, loaded, index) {
452 const test_name = path.basename(test_file, ".js");
454 process.stdout.write('Checking "' + test_name + '" ... ');
455 return runChecks(test_file, loaded, index);
458 function main(argv) {
459 var opts = parseOptions(argv.slice(2));
464 var [loaded, index] = load_files(
466 opts["resource_suffix"],
470 if (opts["test_file"].length !== 0) {
471 errors += checkFile(opts["test_file"], opts, loaded, index);
473 if (opts["test_folder"].length !== 0) {
474 fs.readdirSync(opts["test_folder"]).forEach(function(file) {
475 if (!file.endsWith(".js")) {
478 errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
481 return errors > 0 ? 1 : 0;
484 process.exit(main(process.argv));