暫無描述

RootTransformer.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2. var _keywords = require('../parser/tokenizer/keywords');
  3. var _types = require('../parser/tokenizer/types');
  4. var _getClassInfo = require('../util/getClassInfo'); var _getClassInfo2 = _interopRequireDefault(_getClassInfo);
  5. var _CJSImportTransformer = require('./CJSImportTransformer'); var _CJSImportTransformer2 = _interopRequireDefault(_CJSImportTransformer);
  6. var _ESMImportTransformer = require('./ESMImportTransformer'); var _ESMImportTransformer2 = _interopRequireDefault(_ESMImportTransformer);
  7. var _FlowTransformer = require('./FlowTransformer'); var _FlowTransformer2 = _interopRequireDefault(_FlowTransformer);
  8. var _JestHoistTransformer = require('./JestHoistTransformer'); var _JestHoistTransformer2 = _interopRequireDefault(_JestHoistTransformer);
  9. var _JSXTransformer = require('./JSXTransformer'); var _JSXTransformer2 = _interopRequireDefault(_JSXTransformer);
  10. var _NumericSeparatorTransformer = require('./NumericSeparatorTransformer'); var _NumericSeparatorTransformer2 = _interopRequireDefault(_NumericSeparatorTransformer);
  11. var _OptionalCatchBindingTransformer = require('./OptionalCatchBindingTransformer'); var _OptionalCatchBindingTransformer2 = _interopRequireDefault(_OptionalCatchBindingTransformer);
  12. var _OptionalChainingNullishTransformer = require('./OptionalChainingNullishTransformer'); var _OptionalChainingNullishTransformer2 = _interopRequireDefault(_OptionalChainingNullishTransformer);
  13. var _ReactDisplayNameTransformer = require('./ReactDisplayNameTransformer'); var _ReactDisplayNameTransformer2 = _interopRequireDefault(_ReactDisplayNameTransformer);
  14. var _ReactHotLoaderTransformer = require('./ReactHotLoaderTransformer'); var _ReactHotLoaderTransformer2 = _interopRequireDefault(_ReactHotLoaderTransformer);
  15. var _TypeScriptTransformer = require('./TypeScriptTransformer'); var _TypeScriptTransformer2 = _interopRequireDefault(_TypeScriptTransformer);
  16. class RootTransformer {
  17. __init() {this.transformers = []}
  18. __init2() {this.generatedVariables = []}
  19. constructor(
  20. sucraseContext,
  21. transforms,
  22. enableLegacyBabel5ModuleInterop,
  23. options,
  24. ) {;RootTransformer.prototype.__init.call(this);RootTransformer.prototype.__init2.call(this);
  25. this.nameManager = sucraseContext.nameManager;
  26. this.helperManager = sucraseContext.helperManager;
  27. const {tokenProcessor, importProcessor} = sucraseContext;
  28. this.tokens = tokenProcessor;
  29. this.isImportsTransformEnabled = transforms.includes("imports");
  30. this.isReactHotLoaderTransformEnabled = transforms.includes("react-hot-loader");
  31. this.disableESTransforms = Boolean(options.disableESTransforms);
  32. if (!options.disableESTransforms) {
  33. this.transformers.push(
  34. new (0, _OptionalChainingNullishTransformer2.default)(tokenProcessor, this.nameManager),
  35. );
  36. this.transformers.push(new (0, _NumericSeparatorTransformer2.default)(tokenProcessor));
  37. this.transformers.push(new (0, _OptionalCatchBindingTransformer2.default)(tokenProcessor, this.nameManager));
  38. }
  39. if (transforms.includes("jsx")) {
  40. if (options.jsxRuntime !== "preserve") {
  41. this.transformers.push(
  42. new (0, _JSXTransformer2.default)(this, tokenProcessor, importProcessor, this.nameManager, options),
  43. );
  44. }
  45. this.transformers.push(
  46. new (0, _ReactDisplayNameTransformer2.default)(this, tokenProcessor, importProcessor, options),
  47. );
  48. }
  49. let reactHotLoaderTransformer = null;
  50. if (transforms.includes("react-hot-loader")) {
  51. if (!options.filePath) {
  52. throw new Error("filePath is required when using the react-hot-loader transform.");
  53. }
  54. reactHotLoaderTransformer = new (0, _ReactHotLoaderTransformer2.default)(tokenProcessor, options.filePath);
  55. this.transformers.push(reactHotLoaderTransformer);
  56. }
  57. // Note that we always want to enable the imports transformer, even when the import transform
  58. // itself isn't enabled, since we need to do type-only import pruning for both Flow and
  59. // TypeScript.
  60. if (transforms.includes("imports")) {
  61. if (importProcessor === null) {
  62. throw new Error("Expected non-null importProcessor with imports transform enabled.");
  63. }
  64. this.transformers.push(
  65. new (0, _CJSImportTransformer2.default)(
  66. this,
  67. tokenProcessor,
  68. importProcessor,
  69. this.nameManager,
  70. this.helperManager,
  71. reactHotLoaderTransformer,
  72. enableLegacyBabel5ModuleInterop,
  73. Boolean(options.enableLegacyTypeScriptModuleInterop),
  74. transforms.includes("typescript"),
  75. Boolean(options.preserveDynamicImport),
  76. ),
  77. );
  78. } else {
  79. this.transformers.push(
  80. new (0, _ESMImportTransformer2.default)(
  81. tokenProcessor,
  82. this.nameManager,
  83. this.helperManager,
  84. reactHotLoaderTransformer,
  85. transforms.includes("typescript"),
  86. options,
  87. ),
  88. );
  89. }
  90. if (transforms.includes("flow")) {
  91. this.transformers.push(
  92. new (0, _FlowTransformer2.default)(this, tokenProcessor, transforms.includes("imports")),
  93. );
  94. }
  95. if (transforms.includes("typescript")) {
  96. this.transformers.push(
  97. new (0, _TypeScriptTransformer2.default)(this, tokenProcessor, transforms.includes("imports")),
  98. );
  99. }
  100. if (transforms.includes("jest")) {
  101. this.transformers.push(
  102. new (0, _JestHoistTransformer2.default)(this, tokenProcessor, this.nameManager, importProcessor),
  103. );
  104. }
  105. }
  106. transform() {
  107. this.tokens.reset();
  108. this.processBalancedCode();
  109. const shouldAddUseStrict = this.isImportsTransformEnabled;
  110. // "use strict" always needs to be first, so override the normal transformer order.
  111. let prefix = shouldAddUseStrict ? '"use strict";' : "";
  112. for (const transformer of this.transformers) {
  113. prefix += transformer.getPrefixCode();
  114. }
  115. prefix += this.helperManager.emitHelpers();
  116. prefix += this.generatedVariables.map((v) => ` var ${v};`).join("");
  117. for (const transformer of this.transformers) {
  118. prefix += transformer.getHoistedCode();
  119. }
  120. let suffix = "";
  121. for (const transformer of this.transformers) {
  122. suffix += transformer.getSuffixCode();
  123. }
  124. const result = this.tokens.finish();
  125. let {code} = result;
  126. if (code.startsWith("#!")) {
  127. let newlineIndex = code.indexOf("\n");
  128. if (newlineIndex === -1) {
  129. newlineIndex = code.length;
  130. code += "\n";
  131. }
  132. return {
  133. code: code.slice(0, newlineIndex + 1) + prefix + code.slice(newlineIndex + 1) + suffix,
  134. // The hashbang line has no tokens, so shifting the tokens to account
  135. // for prefix can happen normally.
  136. mappings: this.shiftMappings(result.mappings, prefix.length),
  137. };
  138. } else {
  139. return {
  140. code: prefix + code + suffix,
  141. mappings: this.shiftMappings(result.mappings, prefix.length),
  142. };
  143. }
  144. }
  145. processBalancedCode() {
  146. let braceDepth = 0;
  147. let parenDepth = 0;
  148. while (!this.tokens.isAtEnd()) {
  149. if (this.tokens.matches1(_types.TokenType.braceL) || this.tokens.matches1(_types.TokenType.dollarBraceL)) {
  150. braceDepth++;
  151. } else if (this.tokens.matches1(_types.TokenType.braceR)) {
  152. if (braceDepth === 0) {
  153. return;
  154. }
  155. braceDepth--;
  156. }
  157. if (this.tokens.matches1(_types.TokenType.parenL)) {
  158. parenDepth++;
  159. } else if (this.tokens.matches1(_types.TokenType.parenR)) {
  160. if (parenDepth === 0) {
  161. return;
  162. }
  163. parenDepth--;
  164. }
  165. this.processToken();
  166. }
  167. }
  168. processToken() {
  169. if (this.tokens.matches1(_types.TokenType._class)) {
  170. this.processClass();
  171. return;
  172. }
  173. for (const transformer of this.transformers) {
  174. const wasProcessed = transformer.process();
  175. if (wasProcessed) {
  176. return;
  177. }
  178. }
  179. this.tokens.copyToken();
  180. }
  181. /**
  182. * Skip past a class with a name and return that name.
  183. */
  184. processNamedClass() {
  185. if (!this.tokens.matches2(_types.TokenType._class, _types.TokenType.name)) {
  186. throw new Error("Expected identifier for exported class name.");
  187. }
  188. const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
  189. this.processClass();
  190. return name;
  191. }
  192. processClass() {
  193. const classInfo = _getClassInfo2.default.call(void 0, this, this.tokens, this.nameManager, this.disableESTransforms);
  194. // Both static and instance initializers need a class name to use to invoke the initializer, so
  195. // assign to one if necessary.
  196. const needsCommaExpression =
  197. (classInfo.headerInfo.isExpression || !classInfo.headerInfo.className) &&
  198. classInfo.staticInitializerNames.length + classInfo.instanceInitializerNames.length > 0;
  199. let className = classInfo.headerInfo.className;
  200. if (needsCommaExpression) {
  201. className = this.nameManager.claimFreeName("_class");
  202. this.generatedVariables.push(className);
  203. this.tokens.appendCode(` (${className} =`);
  204. }
  205. const classToken = this.tokens.currentToken();
  206. const contextId = classToken.contextId;
  207. if (contextId == null) {
  208. throw new Error("Expected class to have a context ID.");
  209. }
  210. this.tokens.copyExpectedToken(_types.TokenType._class);
  211. while (!this.tokens.matchesContextIdAndLabel(_types.TokenType.braceL, contextId)) {
  212. this.processToken();
  213. }
  214. this.processClassBody(classInfo, className);
  215. const staticInitializerStatements = classInfo.staticInitializerNames.map(
  216. (name) => `${className}.${name}()`,
  217. );
  218. if (needsCommaExpression) {
  219. this.tokens.appendCode(
  220. `, ${staticInitializerStatements.map((s) => `${s}, `).join("")}${className})`,
  221. );
  222. } else if (classInfo.staticInitializerNames.length > 0) {
  223. this.tokens.appendCode(` ${staticInitializerStatements.map((s) => `${s};`).join(" ")}`);
  224. }
  225. }
  226. /**
  227. * We want to just handle class fields in all contexts, since TypeScript supports them. Later,
  228. * when some JS implementations support class fields, this should be made optional.
  229. */
  230. processClassBody(classInfo, className) {
  231. const {
  232. headerInfo,
  233. constructorInsertPos,
  234. constructorInitializerStatements,
  235. fields,
  236. instanceInitializerNames,
  237. rangesToRemove,
  238. } = classInfo;
  239. let fieldIndex = 0;
  240. let rangeToRemoveIndex = 0;
  241. const classContextId = this.tokens.currentToken().contextId;
  242. if (classContextId == null) {
  243. throw new Error("Expected non-null context ID on class.");
  244. }
  245. this.tokens.copyExpectedToken(_types.TokenType.braceL);
  246. if (this.isReactHotLoaderTransformEnabled) {
  247. this.tokens.appendCode(
  248. "__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}",
  249. );
  250. }
  251. const needsConstructorInit =
  252. constructorInitializerStatements.length + instanceInitializerNames.length > 0;
  253. if (constructorInsertPos === null && needsConstructorInit) {
  254. const constructorInitializersCode = this.makeConstructorInitCode(
  255. constructorInitializerStatements,
  256. instanceInitializerNames,
  257. className,
  258. );
  259. if (headerInfo.hasSuperclass) {
  260. const argsName = this.nameManager.claimFreeName("args");
  261. this.tokens.appendCode(
  262. `constructor(...${argsName}) { super(...${argsName}); ${constructorInitializersCode}; }`,
  263. );
  264. } else {
  265. this.tokens.appendCode(`constructor() { ${constructorInitializersCode}; }`);
  266. }
  267. }
  268. while (!this.tokens.matchesContextIdAndLabel(_types.TokenType.braceR, classContextId)) {
  269. if (fieldIndex < fields.length && this.tokens.currentIndex() === fields[fieldIndex].start) {
  270. let needsCloseBrace = false;
  271. if (this.tokens.matches1(_types.TokenType.bracketL)) {
  272. this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this`);
  273. } else if (this.tokens.matches1(_types.TokenType.string) || this.tokens.matches1(_types.TokenType.num)) {
  274. this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this[`);
  275. needsCloseBrace = true;
  276. } else {
  277. this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this.`);
  278. }
  279. while (this.tokens.currentIndex() < fields[fieldIndex].end) {
  280. if (needsCloseBrace && this.tokens.currentIndex() === fields[fieldIndex].equalsIndex) {
  281. this.tokens.appendCode("]");
  282. }
  283. this.processToken();
  284. }
  285. this.tokens.appendCode("}");
  286. fieldIndex++;
  287. } else if (
  288. rangeToRemoveIndex < rangesToRemove.length &&
  289. this.tokens.currentIndex() >= rangesToRemove[rangeToRemoveIndex].start
  290. ) {
  291. if (this.tokens.currentIndex() < rangesToRemove[rangeToRemoveIndex].end) {
  292. this.tokens.removeInitialToken();
  293. }
  294. while (this.tokens.currentIndex() < rangesToRemove[rangeToRemoveIndex].end) {
  295. this.tokens.removeToken();
  296. }
  297. rangeToRemoveIndex++;
  298. } else if (this.tokens.currentIndex() === constructorInsertPos) {
  299. this.tokens.copyToken();
  300. if (needsConstructorInit) {
  301. this.tokens.appendCode(
  302. `;${this.makeConstructorInitCode(
  303. constructorInitializerStatements,
  304. instanceInitializerNames,
  305. className,
  306. )};`,
  307. );
  308. }
  309. this.processToken();
  310. } else {
  311. this.processToken();
  312. }
  313. }
  314. this.tokens.copyExpectedToken(_types.TokenType.braceR);
  315. }
  316. makeConstructorInitCode(
  317. constructorInitializerStatements,
  318. instanceInitializerNames,
  319. className,
  320. ) {
  321. return [
  322. ...constructorInitializerStatements,
  323. ...instanceInitializerNames.map((name) => `${className}.prototype.${name}.call(this)`),
  324. ].join(";");
  325. }
  326. /**
  327. * Normally it's ok to simply remove type tokens, but we need to be more careful when dealing with
  328. * arrow function return types since they can confuse the parser. In that case, we want to move
  329. * the close-paren to the same line as the arrow.
  330. *
  331. * See https://github.com/alangpierce/sucrase/issues/391 for more details.
  332. */
  333. processPossibleArrowParamEnd() {
  334. if (this.tokens.matches2(_types.TokenType.parenR, _types.TokenType.colon) && this.tokens.tokenAtRelativeIndex(1).isType) {
  335. let nextNonTypeIndex = this.tokens.currentIndex() + 1;
  336. // Look ahead to see if this is an arrow function or something else.
  337. while (this.tokens.tokens[nextNonTypeIndex].isType) {
  338. nextNonTypeIndex++;
  339. }
  340. if (this.tokens.matches1AtIndex(nextNonTypeIndex, _types.TokenType.arrow)) {
  341. this.tokens.removeInitialToken();
  342. while (this.tokens.currentIndex() < nextNonTypeIndex) {
  343. this.tokens.removeToken();
  344. }
  345. this.tokens.replaceTokenTrimmingLeftWhitespace(") =>");
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. /**
  352. * An async arrow function might be of the form:
  353. *
  354. * async <
  355. * T
  356. * >() => {}
  357. *
  358. * in which case, removing the type parameters will cause a syntax error. Detect this case and
  359. * move the open-paren earlier.
  360. */
  361. processPossibleAsyncArrowWithTypeParams() {
  362. if (
  363. !this.tokens.matchesContextual(_keywords.ContextualKeyword._async) &&
  364. !this.tokens.matches1(_types.TokenType._async)
  365. ) {
  366. return false;
  367. }
  368. const nextToken = this.tokens.tokenAtRelativeIndex(1);
  369. if (nextToken.type !== _types.TokenType.lessThan || !nextToken.isType) {
  370. return false;
  371. }
  372. let nextNonTypeIndex = this.tokens.currentIndex() + 1;
  373. // Look ahead to see if this is an arrow function or something else.
  374. while (this.tokens.tokens[nextNonTypeIndex].isType) {
  375. nextNonTypeIndex++;
  376. }
  377. if (this.tokens.matches1AtIndex(nextNonTypeIndex, _types.TokenType.parenL)) {
  378. this.tokens.replaceToken("async (");
  379. this.tokens.removeInitialToken();
  380. while (this.tokens.currentIndex() < nextNonTypeIndex) {
  381. this.tokens.removeToken();
  382. }
  383. this.tokens.removeToken();
  384. // We ate a ( token, so we need to process the tokens in between and then the ) token so that
  385. // we remain balanced.
  386. this.processBalancedCode();
  387. this.processToken();
  388. return true;
  389. }
  390. return false;
  391. }
  392. processPossibleTypeRange() {
  393. if (this.tokens.currentToken().isType) {
  394. this.tokens.removeInitialToken();
  395. while (this.tokens.currentToken().isType) {
  396. this.tokens.removeToken();
  397. }
  398. return true;
  399. }
  400. return false;
  401. }
  402. shiftMappings(
  403. mappings,
  404. prefixLength,
  405. ) {
  406. for (let i = 0; i < mappings.length; i++) {
  407. const mapping = mappings[i];
  408. if (mapping !== undefined) {
  409. mappings[i] = mapping + prefixLength;
  410. }
  411. }
  412. return mappings;
  413. }
  414. } exports.default = RootTransformer;