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 lookForEntry(entry, data) {
194 for (var i = 0; i < data.length; ++i) {
196 for (var key in entry) {
197 if (!entry.hasOwnProperty(key)) {
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'];
206 value = data[i]['parent']['name'];
209 if (value !== entry[key]) {
214 if (allGood === true) {
221 function loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate) {
222 if (searchIndex[searchIndex.length - 1].length === 0) {
226 var fullSearchIndex = searchIndex.join("\n") + '\nexports.rawSearchIndex = searchIndex;';
227 searchIndex = loadContent(fullSearchIndex);
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",
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"];
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);
249 var loaded = loadContent(finalJS);
250 var index = loaded.buildIndex(searchIndex.rawSearchIndex);
252 return [loaded, index];
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;
260 var results = loaded.execSearch(loaded.getQuery(query), index, filter_crate);
263 for (var key in expected) {
264 if (!expected.hasOwnProperty(key)) {
267 if (!results.hasOwnProperty(key)) {
268 error_text.push('==> Unknown key "' + key + '"');
271 var entry = expected[key];
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]) + "'");
286 prev_pos = entry_pos;
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"));
301 if (displaySuccess) {
309 function runChecks(testFile, loaded, index) {
310 var loadedFile = loadContent(
311 readFile(testFile) + 'exports.QUERY = QUERY;exports.EXPECTED = EXPECTED;');
313 const expected = loadedFile.EXPECTED;
314 const query = loadedFile.QUERY;
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");
321 } else if (query.length !== expected.length) {
322 console.log("FAILED");
323 console.log("==> QUERY variable should have the same length as EXPECTED");
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) {
336 var error_text = runSearch(query, expected, index, loaded, loadedFile, "");
337 return checkResult(error_text, loadedFile, true);
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");
346 return loadMainJsAndIndex(mainJs, searchIndex, storageJs, crate);
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");
359 function parseOptions(args) {
362 "resource_suffix": "",
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",
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") {
382 if (i >= args.length) {
383 console.log("Missing argument after `" + args[i - 1] + "` option.");
386 opts[correspondances[args[i - 1]]] = args[i];
387 } else if (args[i] === "--help") {
391 console.log("Unknown option `" + args[i] + "`.");
392 console.log("Use `--help` to see the list of options");
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.");
408 function checkFile(test_file, opts, loaded, index) {
409 const test_name = path.basename(test_file, ".js");
411 process.stdout.write('Checking "' + test_name + '" ... ');
412 return runChecks(test_file, loaded, index);
415 function main(argv) {
416 var opts = parseOptions(argv.slice(2));
421 var [loaded, index] = load_files(
423 opts["resource_suffix"],
427 if (opts["test_file"].length !== 0) {
428 errors += checkFile(opts["test_file"], opts, loaded, index);
430 if (opts["test_folder"].length !== 0) {
431 fs.readdirSync(opts["test_folder"]).forEach(function(file) {
432 if (!file.endsWith(".js")) {
435 errors += checkFile(path.join(opts["test_folder"], file), opts, loaded, index);
438 return errors > 0 ? 1 : 0;
441 process.exit(main(process.argv));