comparators.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { compareRuntime } = require("./runtime");
  7. /** @typedef {import("../Chunk")} Chunk */
  8. /** @typedef {import("../Chunk").ChunkId} ChunkId */
  9. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  10. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  11. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  12. /** @typedef {import("../Module")} Module */
  13. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  14. /** @template T @typedef {function(T, T): -1|0|1} Comparator */
  15. /** @template TArg @template T @typedef {function(TArg, T, T): -1|0|1} RawParameterizedComparator */
  16. /** @template TArg @template T @typedef {function(TArg): Comparator<T>} ParameterizedComparator */
  17. /**
  18. * @template T
  19. * @param {RawParameterizedComparator<any, T>} fn comparator with argument
  20. * @returns {ParameterizedComparator<any, T>} comparator
  21. */
  22. const createCachedParameterizedComparator = fn => {
  23. /** @type {WeakMap<object, Comparator<T>>} */
  24. const map = new WeakMap();
  25. return arg => {
  26. const cachedResult = map.get(arg);
  27. if (cachedResult !== undefined) return cachedResult;
  28. /**
  29. * @param {T} a first item
  30. * @param {T} b second item
  31. * @returns {-1|0|1} compare result
  32. */
  33. const result = fn.bind(null, arg);
  34. map.set(arg, result);
  35. return result;
  36. };
  37. };
  38. /**
  39. * @param {Chunk} a chunk
  40. * @param {Chunk} b chunk
  41. * @returns {-1|0|1} compare result
  42. */
  43. exports.compareChunksById = (a, b) => {
  44. return compareIds(
  45. /** @type {ChunkId} */ (a.id),
  46. /** @type {ChunkId} */ (b.id)
  47. );
  48. };
  49. /**
  50. * @param {Module} a module
  51. * @param {Module} b module
  52. * @returns {-1|0|1} compare result
  53. */
  54. exports.compareModulesByIdentifier = (a, b) => {
  55. return compareIds(a.identifier(), b.identifier());
  56. };
  57. /**
  58. * @param {ChunkGraph} chunkGraph the chunk graph
  59. * @param {Module} a module
  60. * @param {Module} b module
  61. * @returns {-1|0|1} compare result
  62. */
  63. const compareModulesById = (chunkGraph, a, b) => {
  64. return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b));
  65. };
  66. /** @type {ParameterizedComparator<ChunkGraph, Module>} */
  67. exports.compareModulesById =
  68. createCachedParameterizedComparator(compareModulesById);
  69. /**
  70. * @param {number} a number
  71. * @param {number} b number
  72. * @returns {-1|0|1} compare result
  73. */
  74. const compareNumbers = (a, b) => {
  75. if (typeof a !== typeof b) {
  76. return typeof a < typeof b ? -1 : 1;
  77. }
  78. if (a < b) return -1;
  79. if (a > b) return 1;
  80. return 0;
  81. };
  82. exports.compareNumbers = compareNumbers;
  83. /**
  84. * @param {string} a string
  85. * @param {string} b string
  86. * @returns {-1|0|1} compare result
  87. */
  88. const compareStringsNumeric = (a, b) => {
  89. const aLength = a.length;
  90. const bLength = b.length;
  91. let aChar = 0;
  92. let bChar = 0;
  93. let aIsDigit = false;
  94. let bIsDigit = false;
  95. let i = 0;
  96. let j = 0;
  97. while (i < aLength && j < bLength) {
  98. aChar = a.charCodeAt(i);
  99. bChar = b.charCodeAt(j);
  100. aIsDigit = aChar >= 48 && aChar <= 57;
  101. bIsDigit = bChar >= 48 && bChar <= 57;
  102. if (!aIsDigit && !bIsDigit) {
  103. if (aChar < bChar) return -1;
  104. if (aChar > bChar) return 1;
  105. i++;
  106. j++;
  107. } else if (aIsDigit && !bIsDigit) {
  108. // This segment of a is shorter than in b
  109. return 1;
  110. } else if (!aIsDigit && bIsDigit) {
  111. // This segment of b is shorter than in a
  112. return -1;
  113. } else {
  114. let aNumber = aChar - 48;
  115. let bNumber = bChar - 48;
  116. while (++i < aLength) {
  117. aChar = a.charCodeAt(i);
  118. if (aChar < 48 || aChar > 57) break;
  119. aNumber = aNumber * 10 + aChar - 48;
  120. }
  121. while (++j < bLength) {
  122. bChar = b.charCodeAt(j);
  123. if (bChar < 48 || bChar > 57) break;
  124. bNumber = bNumber * 10 + bChar - 48;
  125. }
  126. if (aNumber < bNumber) return -1;
  127. if (aNumber > bNumber) return 1;
  128. }
  129. }
  130. if (j < bLength) {
  131. // a is shorter than b
  132. bChar = b.charCodeAt(j);
  133. bIsDigit = bChar >= 48 && bChar <= 57;
  134. return bIsDigit ? -1 : 1;
  135. }
  136. if (i < aLength) {
  137. // b is shorter than a
  138. aChar = a.charCodeAt(i);
  139. aIsDigit = aChar >= 48 && aChar <= 57;
  140. return aIsDigit ? 1 : -1;
  141. }
  142. return 0;
  143. };
  144. exports.compareStringsNumeric = compareStringsNumeric;
  145. /**
  146. * @param {ModuleGraph} moduleGraph the module graph
  147. * @param {Module} a module
  148. * @param {Module} b module
  149. * @returns {-1|0|1} compare result
  150. */
  151. const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => {
  152. const cmp = compareNumbers(
  153. /** @type {number} */ (moduleGraph.getPostOrderIndex(a)),
  154. /** @type {number} */ (moduleGraph.getPostOrderIndex(b))
  155. );
  156. if (cmp !== 0) return cmp;
  157. return compareIds(a.identifier(), b.identifier());
  158. };
  159. /** @type {ParameterizedComparator<ModuleGraph, Module>} */
  160. exports.compareModulesByPostOrderIndexOrIdentifier =
  161. createCachedParameterizedComparator(
  162. compareModulesByPostOrderIndexOrIdentifier
  163. );
  164. /**
  165. * @param {ModuleGraph} moduleGraph the module graph
  166. * @param {Module} a module
  167. * @param {Module} b module
  168. * @returns {-1|0|1} compare result
  169. */
  170. const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => {
  171. const cmp = compareNumbers(
  172. /** @type {number} */ (moduleGraph.getPreOrderIndex(a)),
  173. /** @type {number} */ (moduleGraph.getPreOrderIndex(b))
  174. );
  175. if (cmp !== 0) return cmp;
  176. return compareIds(a.identifier(), b.identifier());
  177. };
  178. /** @type {ParameterizedComparator<ModuleGraph, Module>} */
  179. exports.compareModulesByPreOrderIndexOrIdentifier =
  180. createCachedParameterizedComparator(
  181. compareModulesByPreOrderIndexOrIdentifier
  182. );
  183. /**
  184. * @param {ChunkGraph} chunkGraph the chunk graph
  185. * @param {Module} a module
  186. * @param {Module} b module
  187. * @returns {-1|0|1} compare result
  188. */
  189. const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => {
  190. const cmp = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b));
  191. if (cmp !== 0) return cmp;
  192. return compareIds(a.identifier(), b.identifier());
  193. };
  194. /** @type {ParameterizedComparator<ChunkGraph, Module>} */
  195. exports.compareModulesByIdOrIdentifier = createCachedParameterizedComparator(
  196. compareModulesByIdOrIdentifier
  197. );
  198. /**
  199. * @param {ChunkGraph} chunkGraph the chunk graph
  200. * @param {Chunk} a chunk
  201. * @param {Chunk} b chunk
  202. * @returns {-1|0|1} compare result
  203. */
  204. const compareChunks = (chunkGraph, a, b) => {
  205. return chunkGraph.compareChunks(a, b);
  206. };
  207. /** @type {ParameterizedComparator<ChunkGraph, Chunk>} */
  208. exports.compareChunks = createCachedParameterizedComparator(compareChunks);
  209. /**
  210. * @param {string|number} a first id
  211. * @param {string|number} b second id
  212. * @returns {-1|0|1} compare result
  213. */
  214. const compareIds = (a, b) => {
  215. if (typeof a !== typeof b) {
  216. return typeof a < typeof b ? -1 : 1;
  217. }
  218. if (a < b) return -1;
  219. if (a > b) return 1;
  220. return 0;
  221. };
  222. exports.compareIds = compareIds;
  223. /**
  224. * @param {string} a first string
  225. * @param {string} b second string
  226. * @returns {-1|0|1} compare result
  227. */
  228. const compareStrings = (a, b) => {
  229. if (a < b) return -1;
  230. if (a > b) return 1;
  231. return 0;
  232. };
  233. exports.compareStrings = compareStrings;
  234. /**
  235. * @param {ChunkGroup} a first chunk group
  236. * @param {ChunkGroup} b second chunk group
  237. * @returns {-1|0|1} compare result
  238. */
  239. const compareChunkGroupsByIndex = (a, b) => {
  240. return /** @type {number} */ (a.index) < /** @type {number} */ (b.index)
  241. ? -1
  242. : 1;
  243. };
  244. exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex;
  245. /**
  246. * @template K1 {Object}
  247. * @template K2
  248. * @template T
  249. */
  250. class TwoKeyWeakMap {
  251. constructor() {
  252. /**
  253. * @private
  254. * @type {WeakMap<any, WeakMap<any, T | undefined>>}
  255. */
  256. this._map = new WeakMap();
  257. }
  258. /**
  259. * @param {K1} key1 first key
  260. * @param {K2} key2 second key
  261. * @returns {T | undefined} value
  262. */
  263. get(key1, key2) {
  264. const childMap = this._map.get(key1);
  265. if (childMap === undefined) {
  266. return undefined;
  267. }
  268. return childMap.get(key2);
  269. }
  270. /**
  271. * @param {K1} key1 first key
  272. * @param {K2} key2 second key
  273. * @param {T | undefined} value new value
  274. * @returns {void}
  275. */
  276. set(key1, key2, value) {
  277. let childMap = this._map.get(key1);
  278. if (childMap === undefined) {
  279. childMap = new WeakMap();
  280. this._map.set(key1, childMap);
  281. }
  282. childMap.set(key2, value);
  283. }
  284. }
  285. /** @type {TwoKeyWeakMap<Comparator<any>, Comparator<any>, Comparator<any>>}} */
  286. const concatComparatorsCache = new TwoKeyWeakMap();
  287. /**
  288. * @template T
  289. * @param {Comparator<T>} c1 comparator
  290. * @param {Comparator<T>} c2 comparator
  291. * @param {Comparator<T>[]} cRest comparators
  292. * @returns {Comparator<T>} comparator
  293. */
  294. const concatComparators = (c1, c2, ...cRest) => {
  295. if (cRest.length > 0) {
  296. const [c3, ...cRest2] = cRest;
  297. return concatComparators(c1, concatComparators(c2, c3, ...cRest2));
  298. }
  299. const cacheEntry = /** @type {Comparator<T>} */ (
  300. concatComparatorsCache.get(c1, c2)
  301. );
  302. if (cacheEntry !== undefined) return cacheEntry;
  303. /**
  304. * @param {T} a first value
  305. * @param {T} b second value
  306. * @returns {-1|0|1} compare result
  307. */
  308. const result = (a, b) => {
  309. const res = c1(a, b);
  310. if (res !== 0) return res;
  311. return c2(a, b);
  312. };
  313. concatComparatorsCache.set(c1, c2, result);
  314. return result;
  315. };
  316. exports.concatComparators = concatComparators;
  317. /**
  318. * @template A, B
  319. * @typedef {(input: A) => B | undefined | null} Selector
  320. */
  321. /** @type {TwoKeyWeakMap<Selector<any, any>, Comparator<any>, Comparator<any>>}} */
  322. const compareSelectCache = new TwoKeyWeakMap();
  323. /**
  324. * @template T
  325. * @template R
  326. * @param {Selector<T, R>} getter getter for value
  327. * @param {Comparator<R>} comparator comparator
  328. * @returns {Comparator<T>} comparator
  329. */
  330. const compareSelect = (getter, comparator) => {
  331. const cacheEntry = compareSelectCache.get(getter, comparator);
  332. if (cacheEntry !== undefined) return cacheEntry;
  333. /**
  334. * @param {T} a first value
  335. * @param {T} b second value
  336. * @returns {-1|0|1} compare result
  337. */
  338. const result = (a, b) => {
  339. const aValue = getter(a);
  340. const bValue = getter(b);
  341. if (aValue !== undefined && aValue !== null) {
  342. if (bValue !== undefined && bValue !== null) {
  343. return comparator(aValue, bValue);
  344. }
  345. return -1;
  346. } else {
  347. if (bValue !== undefined && bValue !== null) {
  348. return 1;
  349. }
  350. return 0;
  351. }
  352. };
  353. compareSelectCache.set(getter, comparator, result);
  354. return result;
  355. };
  356. exports.compareSelect = compareSelect;
  357. /** @type {WeakMap<Comparator<any>, Comparator<Iterable<any>>>} */
  358. const compareIteratorsCache = new WeakMap();
  359. /**
  360. * @template T
  361. * @param {Comparator<T>} elementComparator comparator for elements
  362. * @returns {Comparator<Iterable<T>>} comparator for iterables of elements
  363. */
  364. const compareIterables = elementComparator => {
  365. const cacheEntry = compareIteratorsCache.get(elementComparator);
  366. if (cacheEntry !== undefined) return cacheEntry;
  367. /**
  368. * @param {Iterable<T>} a first value
  369. * @param {Iterable<T>} b second value
  370. * @returns {-1|0|1} compare result
  371. */
  372. const result = (a, b) => {
  373. const aI = a[Symbol.iterator]();
  374. const bI = b[Symbol.iterator]();
  375. while (true) {
  376. const aItem = aI.next();
  377. const bItem = bI.next();
  378. if (aItem.done) {
  379. return bItem.done ? 0 : -1;
  380. } else if (bItem.done) {
  381. return 1;
  382. }
  383. const res = elementComparator(aItem.value, bItem.value);
  384. if (res !== 0) return res;
  385. }
  386. };
  387. compareIteratorsCache.set(elementComparator, result);
  388. return result;
  389. };
  390. exports.compareIterables = compareIterables;
  391. // TODO this is no longer needed when minimum node.js version is >= 12
  392. // since these versions ship with a stable sort function
  393. /**
  394. * @template T
  395. * @param {Iterable<T>} iterable original ordered list
  396. * @returns {Comparator<T>} comparator
  397. */
  398. exports.keepOriginalOrder = iterable => {
  399. /** @type {Map<T, number>} */
  400. const map = new Map();
  401. let i = 0;
  402. for (const item of iterable) {
  403. map.set(item, i++);
  404. }
  405. return (a, b) =>
  406. compareNumbers(
  407. /** @type {number} */ (map.get(a)),
  408. /** @type {number} */ (map.get(b))
  409. );
  410. };
  411. /**
  412. * @param {ChunkGraph} chunkGraph the chunk graph
  413. * @returns {Comparator<Chunk>} comparator
  414. */
  415. exports.compareChunksNatural = chunkGraph => {
  416. const cmpFn = exports.compareModulesById(chunkGraph);
  417. const cmpIterableFn = compareIterables(cmpFn);
  418. return concatComparators(
  419. compareSelect(
  420. chunk => /** @type {string|number} */ (chunk.name),
  421. compareIds
  422. ),
  423. compareSelect(chunk => chunk.runtime, compareRuntime),
  424. compareSelect(
  425. /**
  426. * @param {Chunk} chunk a chunk
  427. * @returns {Iterable<Module>} modules
  428. */
  429. chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn),
  430. cmpIterableFn
  431. )
  432. );
  433. };
  434. /**
  435. * Compare two locations
  436. * @param {DependencyLocation} a A location node
  437. * @param {DependencyLocation} b A location node
  438. * @returns {-1|0|1} sorting comparator value
  439. */
  440. exports.compareLocations = (a, b) => {
  441. let isObjectA = typeof a === "object" && a !== null;
  442. let isObjectB = typeof b === "object" && b !== null;
  443. if (!isObjectA || !isObjectB) {
  444. if (isObjectA) return 1;
  445. if (isObjectB) return -1;
  446. return 0;
  447. }
  448. if ("start" in a) {
  449. if ("start" in b) {
  450. const ap = a.start;
  451. const bp = b.start;
  452. if (ap.line < bp.line) return -1;
  453. if (ap.line > bp.line) return 1;
  454. if (/** @type {number} */ (ap.column) < /** @type {number} */ (bp.column))
  455. return -1;
  456. if (/** @type {number} */ (ap.column) > /** @type {number} */ (bp.column))
  457. return 1;
  458. } else return -1;
  459. } else if ("start" in b) return 1;
  460. if ("name" in a) {
  461. if ("name" in b) {
  462. if (a.name < b.name) return -1;
  463. if (a.name > b.name) return 1;
  464. } else return -1;
  465. } else if ("name" in b) return 1;
  466. if ("index" in a) {
  467. if ("index" in b) {
  468. if (/** @type {number} */ (a.index) < /** @type {number} */ (b.index))
  469. return -1;
  470. if (/** @type {number} */ (a.index) > /** @type {number} */ (b.index))
  471. return 1;
  472. } else return -1;
  473. } else if ("index" in b) return 1;
  474. return 0;
  475. };