comparators.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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("../ChunkGraph").ModuleId} ModuleId */
  11. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  12. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  13. /** @typedef {import("../Dependency")} Dependency */
  14. /** @typedef {import("../dependencies/HarmonyImportSideEffectDependency")} HarmonyImportSideEffectDependency */
  15. /** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */
  16. /** @typedef {import("../Module")} Module */
  17. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  18. /**
  19. * @typedef {object} DependencySourceOrder
  20. * @property {number} main the main source order
  21. * @property {number} sub the sub source order
  22. */
  23. /**
  24. * @template T
  25. * @typedef {(a: T, b: T) => -1 | 0 | 1} Comparator
  26. */
  27. /**
  28. * @template {object} TArg
  29. * @template T
  30. * @typedef {(tArg: TArg, a: T, b: T) => -1 | 0 | 1} RawParameterizedComparator
  31. */
  32. /**
  33. * @template {object} TArg
  34. * @template T
  35. * @typedef {(tArg: TArg) => Comparator<T>} ParameterizedComparator
  36. */
  37. /**
  38. * @template {object} TArg
  39. * @template {object} T
  40. * @param {RawParameterizedComparator<TArg, T>} fn comparator with argument
  41. * @returns {ParameterizedComparator<TArg, T>} comparator
  42. */
  43. const createCachedParameterizedComparator = fn => {
  44. /** @type {WeakMap<EXPECTED_OBJECT, Comparator<T>>} */
  45. const map = new WeakMap();
  46. return arg => {
  47. const cachedResult = map.get(/** @type {EXPECTED_OBJECT} */ (arg));
  48. if (cachedResult !== undefined) return cachedResult;
  49. /**
  50. * @param {T} a first item
  51. * @param {T} b second item
  52. * @returns {-1|0|1} compare result
  53. */
  54. const result = fn.bind(null, arg);
  55. map.set(/** @type {EXPECTED_OBJECT} */ (arg), result);
  56. return result;
  57. };
  58. };
  59. /**
  60. * @param {string | number} a first id
  61. * @param {string | number} b second id
  62. * @returns {-1 | 0 | 1} compare result
  63. */
  64. const compareIds = (a, b) => {
  65. if (typeof a !== typeof b) {
  66. return typeof a < typeof b ? -1 : 1;
  67. }
  68. if (a < b) return -1;
  69. if (a > b) return 1;
  70. return 0;
  71. };
  72. /**
  73. * @template T
  74. * @param {Comparator<T>} elementComparator comparator for elements
  75. * @returns {Comparator<Iterable<T>>} comparator for iterables of elements
  76. */
  77. const compareIterables = elementComparator => {
  78. const cacheEntry = compareIteratorsCache.get(elementComparator);
  79. if (cacheEntry !== undefined) return cacheEntry;
  80. /**
  81. * @param {Iterable<T>} a first value
  82. * @param {Iterable<T>} b second value
  83. * @returns {-1|0|1} compare result
  84. */
  85. const result = (a, b) => {
  86. const aI = a[Symbol.iterator]();
  87. const bI = b[Symbol.iterator]();
  88. while (true) {
  89. const aItem = aI.next();
  90. const bItem = bI.next();
  91. if (aItem.done) {
  92. return bItem.done ? 0 : -1;
  93. } else if (bItem.done) {
  94. return 1;
  95. }
  96. const res = elementComparator(aItem.value, bItem.value);
  97. if (res !== 0) return res;
  98. }
  99. };
  100. compareIteratorsCache.set(elementComparator, result);
  101. return result;
  102. };
  103. /**
  104. * Compare two locations
  105. * @param {DependencyLocation} a A location node
  106. * @param {DependencyLocation} b A location node
  107. * @returns {-1|0|1} sorting comparator value
  108. */
  109. const compareLocations = (a, b) => {
  110. const isObjectA = typeof a === "object" && a !== null;
  111. const isObjectB = typeof b === "object" && b !== null;
  112. if (!isObjectA || !isObjectB) {
  113. if (isObjectA) return 1;
  114. if (isObjectB) return -1;
  115. return 0;
  116. }
  117. if ("start" in a) {
  118. if ("start" in b) {
  119. const ap = a.start;
  120. const bp = b.start;
  121. if (ap.line < bp.line) return -1;
  122. if (ap.line > bp.line) return 1;
  123. if (
  124. /** @type {number} */ (ap.column) < /** @type {number} */ (bp.column)
  125. ) {
  126. return -1;
  127. }
  128. if (
  129. /** @type {number} */ (ap.column) > /** @type {number} */ (bp.column)
  130. ) {
  131. return 1;
  132. }
  133. } else {
  134. return -1;
  135. }
  136. } else if ("start" in b) {
  137. return 1;
  138. }
  139. if ("name" in a) {
  140. if ("name" in b) {
  141. if (a.name < b.name) return -1;
  142. if (a.name > b.name) return 1;
  143. } else {
  144. return -1;
  145. }
  146. } else if ("name" in b) {
  147. return 1;
  148. }
  149. if ("index" in a) {
  150. if ("index" in b) {
  151. if (/** @type {number} */ (a.index) < /** @type {number} */ (b.index)) {
  152. return -1;
  153. }
  154. if (/** @type {number} */ (a.index) > /** @type {number} */ (b.index)) {
  155. return 1;
  156. }
  157. } else {
  158. return -1;
  159. }
  160. } else if ("index" in b) {
  161. return 1;
  162. }
  163. return 0;
  164. };
  165. /**
  166. * @param {ChunkGraph} chunkGraph the chunk graph
  167. * @param {Module} a module
  168. * @param {Module} b module
  169. * @returns {-1|0|1} compare result
  170. */
  171. const compareModulesById = (chunkGraph, a, b) =>
  172. compareIds(
  173. /** @type {ModuleId} */ (chunkGraph.getModuleId(a)),
  174. /** @type {ModuleId} */ (chunkGraph.getModuleId(b))
  175. );
  176. /**
  177. * @param {number} a number
  178. * @param {number} b number
  179. * @returns {-1|0|1} compare result
  180. */
  181. const compareNumbers = (a, b) => {
  182. if (typeof a !== typeof b) {
  183. return typeof a < typeof b ? -1 : 1;
  184. }
  185. if (a < b) return -1;
  186. if (a > b) return 1;
  187. return 0;
  188. };
  189. /**
  190. * @param {string} a string
  191. * @param {string} b string
  192. * @returns {-1|0|1} compare result
  193. */
  194. const compareStringsNumeric = (a, b) => {
  195. const aLength = a.length;
  196. const bLength = b.length;
  197. let aChar = 0;
  198. let bChar = 0;
  199. let aIsDigit = false;
  200. let bIsDigit = false;
  201. let i = 0;
  202. let j = 0;
  203. while (i < aLength && j < bLength) {
  204. aChar = a.charCodeAt(i);
  205. bChar = b.charCodeAt(j);
  206. aIsDigit = aChar >= 48 && aChar <= 57;
  207. bIsDigit = bChar >= 48 && bChar <= 57;
  208. if (!aIsDigit && !bIsDigit) {
  209. if (aChar < bChar) return -1;
  210. if (aChar > bChar) return 1;
  211. i++;
  212. j++;
  213. } else if (aIsDigit && !bIsDigit) {
  214. // This segment of a is shorter than in b
  215. return 1;
  216. } else if (!aIsDigit && bIsDigit) {
  217. // This segment of b is shorter than in a
  218. return -1;
  219. } else {
  220. let aNumber = aChar - 48;
  221. let bNumber = bChar - 48;
  222. while (++i < aLength) {
  223. aChar = a.charCodeAt(i);
  224. if (aChar < 48 || aChar > 57) break;
  225. aNumber = aNumber * 10 + aChar - 48;
  226. }
  227. while (++j < bLength) {
  228. bChar = b.charCodeAt(j);
  229. if (bChar < 48 || bChar > 57) break;
  230. bNumber = bNumber * 10 + bChar - 48;
  231. }
  232. if (aNumber < bNumber) return -1;
  233. if (aNumber > bNumber) return 1;
  234. }
  235. }
  236. if (j < bLength) {
  237. // a is shorter than b
  238. bChar = b.charCodeAt(j);
  239. bIsDigit = bChar >= 48 && bChar <= 57;
  240. return bIsDigit ? -1 : 1;
  241. }
  242. if (i < aLength) {
  243. // b is shorter than a
  244. aChar = a.charCodeAt(i);
  245. aIsDigit = aChar >= 48 && aChar <= 57;
  246. return aIsDigit ? 1 : -1;
  247. }
  248. return 0;
  249. };
  250. /**
  251. * @param {ModuleGraph} moduleGraph the module graph
  252. * @param {Module} a module
  253. * @param {Module} b module
  254. * @returns {-1|0|1} compare result
  255. */
  256. const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => {
  257. const cmp = compareNumbers(
  258. /** @type {number} */ (moduleGraph.getPostOrderIndex(a)),
  259. /** @type {number} */ (moduleGraph.getPostOrderIndex(b))
  260. );
  261. if (cmp !== 0) return cmp;
  262. return compareIds(a.identifier(), b.identifier());
  263. };
  264. /**
  265. * @param {ModuleGraph} moduleGraph the module graph
  266. * @param {Module} a module
  267. * @param {Module} b module
  268. * @returns {-1|0|1} compare result
  269. */
  270. const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => {
  271. const cmp = compareNumbers(
  272. /** @type {number} */ (moduleGraph.getPreOrderIndex(a)),
  273. /** @type {number} */ (moduleGraph.getPreOrderIndex(b))
  274. );
  275. if (cmp !== 0) return cmp;
  276. return compareIds(a.identifier(), b.identifier());
  277. };
  278. /**
  279. * @param {ChunkGraph} chunkGraph the chunk graph
  280. * @param {Module} a module
  281. * @param {Module} b module
  282. * @returns {-1|0|1} compare result
  283. */
  284. const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => {
  285. const cmp = compareIds(
  286. /** @type {ModuleId} */ (chunkGraph.getModuleId(a)),
  287. /** @type {ModuleId} */ (chunkGraph.getModuleId(b))
  288. );
  289. if (cmp !== 0) return cmp;
  290. return compareIds(a.identifier(), b.identifier());
  291. };
  292. /**
  293. * @param {ChunkGraph} chunkGraph the chunk graph
  294. * @param {Chunk} a chunk
  295. * @param {Chunk} b chunk
  296. * @returns {-1 | 0 | 1} compare result
  297. */
  298. const compareChunks = (chunkGraph, a, b) => chunkGraph.compareChunks(a, b);
  299. /**
  300. * @param {string} a first string
  301. * @param {string} b second string
  302. * @returns {-1|0|1} compare result
  303. */
  304. const compareStrings = (a, b) => {
  305. if (a < b) return -1;
  306. if (a > b) return 1;
  307. return 0;
  308. };
  309. /**
  310. * @param {ChunkGroup} a first chunk group
  311. * @param {ChunkGroup} b second chunk group
  312. * @returns {-1 | 0 | 1} compare result
  313. */
  314. const compareChunkGroupsByIndex = (a, b) =>
  315. /** @type {number} */ (a.index) < /** @type {number} */ (b.index) ? -1 : 1;
  316. /**
  317. * @template {EXPECTED_OBJECT} K1
  318. * @template {EXPECTED_OBJECT} K2
  319. * @template T
  320. */
  321. class TwoKeyWeakMap {
  322. constructor() {
  323. /**
  324. * @private
  325. * @type {WeakMap<K1, WeakMap<K2, T | undefined>>}
  326. */
  327. this._map = new WeakMap();
  328. }
  329. /**
  330. * @param {K1} key1 first key
  331. * @param {K2} key2 second key
  332. * @returns {T | undefined} value
  333. */
  334. get(key1, key2) {
  335. const childMap = this._map.get(key1);
  336. if (childMap === undefined) {
  337. return;
  338. }
  339. return childMap.get(key2);
  340. }
  341. /**
  342. * @param {K1} key1 first key
  343. * @param {K2} key2 second key
  344. * @param {T | undefined} value new value
  345. * @returns {void}
  346. */
  347. set(key1, key2, value) {
  348. let childMap = this._map.get(key1);
  349. if (childMap === undefined) {
  350. childMap = new WeakMap();
  351. this._map.set(key1, childMap);
  352. }
  353. childMap.set(key2, value);
  354. }
  355. }
  356. /** @type {TwoKeyWeakMap<Comparator<EXPECTED_ANY>, Comparator<EXPECTED_ANY>, Comparator<EXPECTED_ANY>>}} */
  357. const concatComparatorsCache = new TwoKeyWeakMap();
  358. /**
  359. * @template T
  360. * @param {Comparator<T>} c1 comparator
  361. * @param {Comparator<T>} c2 comparator
  362. * @param {Comparator<T>[]} cRest comparators
  363. * @returns {Comparator<T>} comparator
  364. */
  365. const concatComparators = (c1, c2, ...cRest) => {
  366. if (cRest.length > 0) {
  367. const [c3, ...cRest2] = cRest;
  368. return concatComparators(c1, concatComparators(c2, c3, ...cRest2));
  369. }
  370. const cacheEntry = /** @type {Comparator<T>} */ (
  371. concatComparatorsCache.get(c1, c2)
  372. );
  373. if (cacheEntry !== undefined) return cacheEntry;
  374. /**
  375. * @param {T} a first value
  376. * @param {T} b second value
  377. * @returns {-1|0|1} compare result
  378. */
  379. const result = (a, b) => {
  380. const res = c1(a, b);
  381. if (res !== 0) return res;
  382. return c2(a, b);
  383. };
  384. concatComparatorsCache.set(c1, c2, result);
  385. return result;
  386. };
  387. /**
  388. * @template A, B
  389. * @typedef {(input: A) => B | undefined | null} Selector
  390. */
  391. /** @type {TwoKeyWeakMap<Selector<EXPECTED_ANY, EXPECTED_ANY>, Comparator<EXPECTED_ANY>, Comparator<EXPECTED_ANY>>}} */
  392. const compareSelectCache = new TwoKeyWeakMap();
  393. /**
  394. * @template T
  395. * @template R
  396. * @param {Selector<T, R>} getter getter for value
  397. * @param {Comparator<R>} comparator comparator
  398. * @returns {Comparator<T>} comparator
  399. */
  400. const compareSelect = (getter, comparator) => {
  401. const cacheEntry = compareSelectCache.get(getter, comparator);
  402. if (cacheEntry !== undefined) return cacheEntry;
  403. /**
  404. * @param {T} a first value
  405. * @param {T} b second value
  406. * @returns {-1|0|1} compare result
  407. */
  408. const result = (a, b) => {
  409. const aValue = getter(a);
  410. const bValue = getter(b);
  411. if (aValue !== undefined && aValue !== null) {
  412. if (bValue !== undefined && bValue !== null) {
  413. return comparator(aValue, bValue);
  414. }
  415. return -1;
  416. }
  417. if (bValue !== undefined && bValue !== null) {
  418. return 1;
  419. }
  420. return 0;
  421. };
  422. compareSelectCache.set(getter, comparator, result);
  423. return result;
  424. };
  425. /** @type {WeakMap<Comparator<EXPECTED_ANY>, Comparator<Iterable<EXPECTED_ANY>>>} */
  426. const compareIteratorsCache = new WeakMap();
  427. // TODO this is no longer needed when minimum node.js version is >= 12
  428. // since these versions ship with a stable sort function
  429. /**
  430. * @template T
  431. * @param {Iterable<T>} iterable original ordered list
  432. * @returns {Comparator<T>} comparator
  433. */
  434. const keepOriginalOrder = iterable => {
  435. /** @type {Map<T, number>} */
  436. const map = new Map();
  437. let i = 0;
  438. for (const item of iterable) {
  439. map.set(item, i++);
  440. }
  441. return (a, b) =>
  442. compareNumbers(
  443. /** @type {number} */ (map.get(a)),
  444. /** @type {number} */ (map.get(b))
  445. );
  446. };
  447. /**
  448. * @param {ChunkGraph} chunkGraph the chunk graph
  449. * @returns {Comparator<Chunk>} comparator
  450. */
  451. const compareChunksNatural = chunkGraph => {
  452. const cmpFn = module.exports.compareModulesById(chunkGraph);
  453. const cmpIterableFn = compareIterables(cmpFn);
  454. return concatComparators(
  455. compareSelect(
  456. chunk => /** @type {string|number} */ (chunk.name),
  457. compareIds
  458. ),
  459. compareSelect(chunk => chunk.runtime, compareRuntime),
  460. compareSelect(
  461. /**
  462. * @param {Chunk} chunk a chunk
  463. * @returns {Iterable<Module>} modules
  464. */
  465. chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn),
  466. cmpIterableFn
  467. )
  468. );
  469. };
  470. /**
  471. * For HarmonyImportSideEffectDependency and HarmonyImportSpecifierDependency, we should prioritize import order to match the behavior of running modules directly in a JS engine without a bundler.
  472. * For other types like ConstDependency, we can instead prioritize usage order.
  473. * https://github.com/webpack/webpack/pull/19686
  474. * @param {Dependency[]} dependencies dependencies
  475. * @param {WeakMap<Dependency, DependencySourceOrder>} dependencySourceOrderMap dependency source order map
  476. * @returns {void}
  477. */
  478. const sortWithSourceOrder = (dependencies, dependencySourceOrderMap) => {
  479. /**
  480. * @param {Dependency} dep dependency
  481. * @returns {number} source order
  482. */
  483. const getSourceOrder = dep => {
  484. if (dependencySourceOrderMap.has(dep)) {
  485. const { main } = /** @type {DependencySourceOrder} */ (
  486. dependencySourceOrderMap.get(dep)
  487. );
  488. return main;
  489. }
  490. return /** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ (
  491. dep
  492. ).sourceOrder;
  493. };
  494. /**
  495. * If the sourceOrder is a number, it means the dependency needs to be sorted.
  496. * @param {number | undefined} sourceOrder sourceOrder
  497. * @returns {boolean} needReSort
  498. */
  499. const needReSort = sourceOrder => {
  500. if (typeof sourceOrder === "number") {
  501. return true;
  502. }
  503. return false;
  504. };
  505. // Extract dependencies with sourceOrder and sort them
  506. const withSourceOrder = [];
  507. // First pass: collect dependencies with sourceOrder
  508. for (let i = 0; i < dependencies.length; i++) {
  509. const dep = dependencies[i];
  510. const sourceOrder = getSourceOrder(dep);
  511. if (needReSort(sourceOrder)) {
  512. withSourceOrder.push({ dep, sourceOrder, originalIndex: i });
  513. }
  514. }
  515. if (withSourceOrder.length <= 1) {
  516. return;
  517. }
  518. // Sort dependencies with sourceOrder
  519. withSourceOrder.sort((a, b) => {
  520. // Handle both dependencies in map case
  521. if (
  522. dependencySourceOrderMap.has(a.dep) &&
  523. dependencySourceOrderMap.has(b.dep)
  524. ) {
  525. const { main: mainA, sub: subA } = /** @type {DependencySourceOrder} */ (
  526. dependencySourceOrderMap.get(a.dep)
  527. );
  528. const { main: mainB, sub: subB } = /** @type {DependencySourceOrder} */ (
  529. dependencySourceOrderMap.get(b.dep)
  530. );
  531. if (mainA === mainB) {
  532. return compareNumbers(subA, subB);
  533. }
  534. return compareNumbers(mainA, mainB);
  535. }
  536. return compareNumbers(a.sourceOrder, b.sourceOrder);
  537. });
  538. // Second pass: build result array
  539. let sortedIndex = 0;
  540. for (let i = 0; i < dependencies.length; i++) {
  541. const dep = dependencies[i];
  542. const sourceOrder = getSourceOrder(dep);
  543. if (needReSort(sourceOrder)) {
  544. dependencies[i] = withSourceOrder[sortedIndex].dep;
  545. sortedIndex++;
  546. }
  547. }
  548. };
  549. module.exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex;
  550. /** @type {ParameterizedComparator<ChunkGraph, Chunk>} */
  551. module.exports.compareChunks =
  552. createCachedParameterizedComparator(compareChunks);
  553. /**
  554. * @param {Chunk} a chunk
  555. * @param {Chunk} b chunk
  556. * @returns {-1|0|1} compare result
  557. */
  558. module.exports.compareChunksById = (a, b) =>
  559. compareIds(/** @type {ChunkId} */ (a.id), /** @type {ChunkId} */ (b.id));
  560. module.exports.compareChunksNatural = compareChunksNatural;
  561. module.exports.compareIds = compareIds;
  562. module.exports.compareIterables = compareIterables;
  563. module.exports.compareLocations = compareLocations;
  564. /** @type {ParameterizedComparator<ChunkGraph, Module>} */
  565. module.exports.compareModulesById =
  566. createCachedParameterizedComparator(compareModulesById);
  567. /** @type {ParameterizedComparator<ChunkGraph, Module>} */
  568. module.exports.compareModulesByIdOrIdentifier =
  569. createCachedParameterizedComparator(compareModulesByIdOrIdentifier);
  570. /**
  571. * @param {Module} a module
  572. * @param {Module} b module
  573. * @returns {-1|0|1} compare result
  574. */
  575. module.exports.compareModulesByIdentifier = (a, b) =>
  576. compareIds(a.identifier(), b.identifier());
  577. /** @type {ParameterizedComparator<ModuleGraph, Module>} */
  578. module.exports.compareModulesByPostOrderIndexOrIdentifier =
  579. createCachedParameterizedComparator(
  580. compareModulesByPostOrderIndexOrIdentifier
  581. );
  582. /** @type {ParameterizedComparator<ModuleGraph, Module>} */
  583. module.exports.compareModulesByPreOrderIndexOrIdentifier =
  584. createCachedParameterizedComparator(
  585. compareModulesByPreOrderIndexOrIdentifier
  586. );
  587. module.exports.compareNumbers = compareNumbers;
  588. module.exports.compareSelect = compareSelect;
  589. module.exports.compareStrings = compareStrings;
  590. module.exports.compareStringsNumeric = compareStringsNumeric;
  591. module.exports.concatComparators = concatComparators;
  592. module.exports.keepOriginalOrder = keepOriginalOrder;
  593. module.exports.sortWithSourceOrder = sortWithSourceOrder;