comparators.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. /** @private @type {WeakMap<any, WeakMap<any, T | undefined>>} */
  253. this._map = new WeakMap();
  254. }
  255. /**
  256. * @param {K1} key1 first key
  257. * @param {K2} key2 second key
  258. * @returns {T | undefined} value
  259. */
  260. get(key1, key2) {
  261. const childMap = this._map.get(key1);
  262. if (childMap === undefined) {
  263. return undefined;
  264. }
  265. return childMap.get(key2);
  266. }
  267. /**
  268. * @param {K1} key1 first key
  269. * @param {K2} key2 second key
  270. * @param {T | undefined} value new value
  271. * @returns {void}
  272. */
  273. set(key1, key2, value) {
  274. let childMap = this._map.get(key1);
  275. if (childMap === undefined) {
  276. childMap = new WeakMap();
  277. this._map.set(key1, childMap);
  278. }
  279. childMap.set(key2, value);
  280. }
  281. }
  282. /** @type {TwoKeyWeakMap<Comparator<any>, Comparator<any>, Comparator<any>>}} */
  283. const concatComparatorsCache = new TwoKeyWeakMap();
  284. /**
  285. * @template T
  286. * @param {Comparator<T>} c1 comparator
  287. * @param {Comparator<T>} c2 comparator
  288. * @param {Comparator<T>[]} cRest comparators
  289. * @returns {Comparator<T>} comparator
  290. */
  291. const concatComparators = (c1, c2, ...cRest) => {
  292. if (cRest.length > 0) {
  293. const [c3, ...cRest2] = cRest;
  294. return concatComparators(c1, concatComparators(c2, c3, ...cRest2));
  295. }
  296. const cacheEntry = /** @type {Comparator<T>} */ (
  297. concatComparatorsCache.get(c1, c2)
  298. );
  299. if (cacheEntry !== undefined) return cacheEntry;
  300. /**
  301. * @param {T} a first value
  302. * @param {T} b second value
  303. * @returns {-1|0|1} compare result
  304. */
  305. const result = (a, b) => {
  306. const res = c1(a, b);
  307. if (res !== 0) return res;
  308. return c2(a, b);
  309. };
  310. concatComparatorsCache.set(c1, c2, result);
  311. return result;
  312. };
  313. exports.concatComparators = concatComparators;
  314. /**
  315. * @template A, B
  316. * @typedef {(input: A) => B | undefined | null} Selector
  317. */
  318. /** @type {TwoKeyWeakMap<Selector<any, any>, Comparator<any>, Comparator<any>>}} */
  319. const compareSelectCache = new TwoKeyWeakMap();
  320. /**
  321. * @template T
  322. * @template R
  323. * @param {Selector<T, R>} getter getter for value
  324. * @param {Comparator<R>} comparator comparator
  325. * @returns {Comparator<T>} comparator
  326. */
  327. const compareSelect = (getter, comparator) => {
  328. const cacheEntry = compareSelectCache.get(getter, comparator);
  329. if (cacheEntry !== undefined) return cacheEntry;
  330. /**
  331. * @param {T} a first value
  332. * @param {T} b second value
  333. * @returns {-1|0|1} compare result
  334. */
  335. const result = (a, b) => {
  336. const aValue = getter(a);
  337. const bValue = getter(b);
  338. if (aValue !== undefined && aValue !== null) {
  339. if (bValue !== undefined && bValue !== null) {
  340. return comparator(aValue, bValue);
  341. }
  342. return -1;
  343. } else {
  344. if (bValue !== undefined && bValue !== null) {
  345. return 1;
  346. }
  347. return 0;
  348. }
  349. };
  350. compareSelectCache.set(getter, comparator, result);
  351. return result;
  352. };
  353. exports.compareSelect = compareSelect;
  354. /** @type {WeakMap<Comparator<any>, Comparator<Iterable<any>>>} */
  355. const compareIteratorsCache = new WeakMap();
  356. /**
  357. * @template T
  358. * @param {Comparator<T>} elementComparator comparator for elements
  359. * @returns {Comparator<Iterable<T>>} comparator for iterables of elements
  360. */
  361. const compareIterables = elementComparator => {
  362. const cacheEntry = compareIteratorsCache.get(elementComparator);
  363. if (cacheEntry !== undefined) return cacheEntry;
  364. /**
  365. * @param {Iterable<T>} a first value
  366. * @param {Iterable<T>} b second value
  367. * @returns {-1|0|1} compare result
  368. */
  369. const result = (a, b) => {
  370. const aI = a[Symbol.iterator]();
  371. const bI = b[Symbol.iterator]();
  372. // eslint-disable-next-line no-constant-condition
  373. while (true) {
  374. const aItem = aI.next();
  375. const bItem = bI.next();
  376. if (aItem.done) {
  377. return bItem.done ? 0 : -1;
  378. } else if (bItem.done) {
  379. return 1;
  380. }
  381. const res = elementComparator(aItem.value, bItem.value);
  382. if (res !== 0) return res;
  383. }
  384. };
  385. compareIteratorsCache.set(elementComparator, result);
  386. return result;
  387. };
  388. exports.compareIterables = compareIterables;
  389. // TODO this is no longer needed when minimum node.js version is >= 12
  390. // since these versions ship with a stable sort function
  391. /**
  392. * @template T
  393. * @param {Iterable<T>} iterable original ordered list
  394. * @returns {Comparator<T>} comparator
  395. */
  396. exports.keepOriginalOrder = iterable => {
  397. /** @type {Map<T, number>} */
  398. const map = new Map();
  399. let i = 0;
  400. for (const item of iterable) {
  401. map.set(item, i++);
  402. }
  403. return (a, b) =>
  404. compareNumbers(
  405. /** @type {number} */ (map.get(a)),
  406. /** @type {number} */ (map.get(b))
  407. );
  408. };
  409. /**
  410. * @param {ChunkGraph} chunkGraph the chunk graph
  411. * @returns {Comparator<Chunk>} comparator
  412. */
  413. exports.compareChunksNatural = chunkGraph => {
  414. const cmpFn = exports.compareModulesById(chunkGraph);
  415. const cmpIterableFn = compareIterables(cmpFn);
  416. return concatComparators(
  417. compareSelect(
  418. chunk => /** @type {string|number} */ (chunk.name),
  419. compareIds
  420. ),
  421. compareSelect(chunk => chunk.runtime, compareRuntime),
  422. compareSelect(
  423. /**
  424. * @param {Chunk} chunk a chunk
  425. * @returns {Iterable<Module>} modules
  426. */
  427. chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn),
  428. cmpIterableFn
  429. )
  430. );
  431. };
  432. /**
  433. * Compare two locations
  434. * @param {DependencyLocation} a A location node
  435. * @param {DependencyLocation} b A location node
  436. * @returns {-1|0|1} sorting comparator value
  437. */
  438. exports.compareLocations = (a, b) => {
  439. let isObjectA = typeof a === "object" && a !== null;
  440. let isObjectB = typeof b === "object" && b !== null;
  441. if (!isObjectA || !isObjectB) {
  442. if (isObjectA) return 1;
  443. if (isObjectB) return -1;
  444. return 0;
  445. }
  446. if ("start" in a) {
  447. if ("start" in b) {
  448. const ap = a.start;
  449. const bp = b.start;
  450. if (ap.line < bp.line) return -1;
  451. if (ap.line > bp.line) return 1;
  452. if (/** @type {number} */ (ap.column) < /** @type {number} */ (bp.column))
  453. return -1;
  454. if (/** @type {number} */ (ap.column) > /** @type {number} */ (bp.column))
  455. return 1;
  456. } else return -1;
  457. } else if ("start" in b) return 1;
  458. if ("name" in a) {
  459. if ("name" in b) {
  460. if (a.name < b.name) return -1;
  461. if (a.name > b.name) return 1;
  462. } else return -1;
  463. } else if ("name" in b) return 1;
  464. if ("index" in a) {
  465. if ("index" in b) {
  466. if (/** @type {number} */ (a.index) < /** @type {number} */ (b.index))
  467. return -1;
  468. if (/** @type {number} */ (a.index) > /** @type {number} */ (b.index))
  469. return 1;
  470. } else return -1;
  471. } else if ("index" in b) return 1;
  472. return 0;
  473. };