transformer.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. const {Parser: AcornParser, isNewLine: acornIsNewLine, getLineInfo: acornGetLineInfo} = require('acorn');
  2. const {full: acornWalkFull} = require('acorn-walk');
  3. const INTERNAL_STATE_NAME = 'VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL';
  4. function assertType(node, type) {
  5. if (!node) throw new Error(`None existent node expected '${type}'`);
  6. if (node.type !== type) throw new Error(`Invalid node type '${node.type}' expected '${type}'`);
  7. return node;
  8. }
  9. function makeNiceSyntaxError(message, code, filename, location, tokenizer) {
  10. const loc = acornGetLineInfo(code, location);
  11. let end = location;
  12. while (end < code.length && !acornIsNewLine(code.charCodeAt(end))) {
  13. end++;
  14. }
  15. let markerEnd = tokenizer.start === location ? tokenizer.end : location + 1;
  16. if (!markerEnd || markerEnd > end) markerEnd = end;
  17. let markerLen = markerEnd - location;
  18. if (markerLen <= 0) markerLen = 1;
  19. if (message === 'Unexpected token') {
  20. const type = tokenizer.type;
  21. if (type.label === 'name' || type.label === 'privateId') {
  22. message = 'Unexpected identifier';
  23. } else if (type.label === 'eof') {
  24. message = 'Unexpected end of input';
  25. } else if (type.label === 'num') {
  26. message = 'Unexpected number';
  27. } else if (type.label === 'string') {
  28. message = 'Unexpected string';
  29. } else if (type.label === 'regexp') {
  30. message = 'Unexpected token \'/\'';
  31. markerLen = 1;
  32. } else {
  33. const token = tokenizer.value || type.label;
  34. message = `Unexpected token '${token}'`;
  35. }
  36. }
  37. const error = new SyntaxError(message);
  38. if (!filename) return error;
  39. const line = code.slice(location - loc.column, end);
  40. const marker = line.slice(0, loc.column).replace(/\S/g, ' ') + '^'.repeat(markerLen);
  41. error.stack = `${filename}:${loc.line}\n${line}\n${marker}\n\n${error.stack}`;
  42. return error;
  43. }
  44. function transformer(args, body, isAsync, isGenerator, filename) {
  45. let code;
  46. let argsOffset;
  47. if (args === null) {
  48. code = body;
  49. } else {
  50. code = isAsync ? '(async function' : '(function';
  51. if (isGenerator) code += '*';
  52. code += ' anonymous(';
  53. code += args;
  54. argsOffset = code.length;
  55. code += '\n) {\n';
  56. code += body;
  57. code += '\n})';
  58. }
  59. const parser = new AcornParser({
  60. __proto__: null,
  61. ecmaVersion: 2022,
  62. allowAwaitOutsideFunction: args === null && isAsync,
  63. allowReturnOutsideFunction: args === null
  64. }, code);
  65. let ast;
  66. try {
  67. ast = parser.parse();
  68. } catch (e) {
  69. // Try to generate a nicer error message.
  70. if (e instanceof SyntaxError && e.pos !== undefined) {
  71. let message = e.message;
  72. const match = message.match(/^(.*) \(\d+:\d+\)$/);
  73. if (match) message = match[1];
  74. e = makeNiceSyntaxError(message, code, filename, e.pos, parser);
  75. }
  76. throw e;
  77. }
  78. if (args !== null) {
  79. const pBody = assertType(ast, 'Program').body;
  80. if (pBody.length !== 1) throw new SyntaxError('Single function literal required');
  81. const expr = pBody[0];
  82. if (expr.type !== 'ExpressionStatement') throw new SyntaxError('Single function literal required');
  83. const func = expr.expression;
  84. if (func.type !== 'FunctionExpression') throw new SyntaxError('Single function literal required');
  85. if (func.body.start !== argsOffset + 3) throw new SyntaxError('Unexpected end of arg string');
  86. }
  87. const insertions = [];
  88. let hasAsync = false;
  89. const TO_LEFT = -100;
  90. const TO_RIGHT = 100;
  91. let internStateValiable = undefined;
  92. acornWalkFull(ast, (node, state, type) => {
  93. if (type === 'Function') {
  94. if (node.async) hasAsync = true;
  95. }
  96. const nodeType = node.type;
  97. if (nodeType === 'CatchClause') {
  98. const param = node.param;
  99. if (param) {
  100. const name = assertType(param, 'Identifier').name;
  101. const cBody = assertType(node.body, 'BlockStatement');
  102. if (cBody.body.length > 0) {
  103. insertions.push({
  104. __proto__: null,
  105. pos: cBody.body[0].start,
  106. order: TO_LEFT,
  107. code: `${name}=${INTERNAL_STATE_NAME}.handleException(${name});`
  108. });
  109. }
  110. }
  111. } else if (nodeType === 'WithStatement') {
  112. insertions.push({
  113. __proto__: null,
  114. pos: node.object.start,
  115. order: TO_LEFT,
  116. code: INTERNAL_STATE_NAME + '.wrapWith('
  117. });
  118. insertions.push({
  119. __proto__: null,
  120. pos: node.object.end,
  121. order: TO_RIGHT,
  122. code: ')'
  123. });
  124. } else if (nodeType === 'Identifier') {
  125. if (node.name === INTERNAL_STATE_NAME) {
  126. if (internStateValiable === undefined || internStateValiable.start > node.start) {
  127. internStateValiable = node;
  128. }
  129. }
  130. } else if (nodeType === 'ImportExpression') {
  131. insertions.push({
  132. __proto__: null,
  133. pos: node.start,
  134. order: TO_RIGHT,
  135. code: INTERNAL_STATE_NAME + '.'
  136. });
  137. }
  138. });
  139. if (internStateValiable) {
  140. throw makeNiceSyntaxError('Use of internal vm2 state variable', code, filename, internStateValiable.start, {
  141. __proto__: null,
  142. start: internStateValiable.start,
  143. end: internStateValiable.end
  144. });
  145. }
  146. if (insertions.length === 0) return {__proto__: null, code, hasAsync};
  147. insertions.sort((a, b) => (a.pos == b.pos ? a.order - b.order : a.pos - b.pos));
  148. let ncode = '';
  149. let curr = 0;
  150. for (let i = 0; i < insertions.length; i++) {
  151. const change = insertions[i];
  152. ncode += code.substring(curr, change.pos) + change.code;
  153. curr = change.pos;
  154. }
  155. ncode += code.substring(curr);
  156. return {__proto__: null, code: ncode, hasAsync};
  157. }
  158. exports.INTERNAL_STATE_NAME = INTERNAL_STATE_NAME;
  159. exports.transformer = transformer;