RootTransformer.js 17 KB

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