web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

587 lines
18 KiB

  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = transformClass;
  6. var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
  7. var _helperReplaceSupers = _interopRequireWildcard(require("@babel/helper-replace-supers"));
  8. var _helperOptimiseCallExpression = _interopRequireDefault(require("@babel/helper-optimise-call-expression"));
  9. var _core = require("@babel/core");
  10. var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));
  11. var _inlineCreateSuperHelpers = _interopRequireDefault(require("./inline-createSuper-helpers"));
  12. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  13. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. function buildConstructor(classRef, constructorBody, node) {
  16. const func = _core.types.functionDeclaration(_core.types.cloneNode(classRef), [], constructorBody);
  17. _core.types.inherits(func, node);
  18. return func;
  19. }
  20. function transformClass(path, file, builtinClasses, isLoose, assumptions) {
  21. const classState = {
  22. parent: undefined,
  23. scope: undefined,
  24. node: undefined,
  25. path: undefined,
  26. file: undefined,
  27. classId: undefined,
  28. classRef: undefined,
  29. superFnId: undefined,
  30. superName: undefined,
  31. superReturns: [],
  32. isDerived: false,
  33. extendsNative: false,
  34. construct: undefined,
  35. constructorBody: undefined,
  36. userConstructor: undefined,
  37. userConstructorPath: undefined,
  38. hasConstructor: false,
  39. staticPropBody: [],
  40. body: [],
  41. superThises: [],
  42. pushedConstructor: false,
  43. pushedInherits: false,
  44. protoAlias: null,
  45. isLoose: false,
  46. methods: {
  47. instance: {
  48. hasComputed: false,
  49. list: [],
  50. map: new Map()
  51. },
  52. static: {
  53. hasComputed: false,
  54. list: [],
  55. map: new Map()
  56. }
  57. }
  58. };
  59. const setState = newState => {
  60. Object.assign(classState, newState);
  61. };
  62. const findThisesVisitor = _core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  63. ThisExpression(path) {
  64. classState.superThises.push(path);
  65. }
  66. }]);
  67. function maybeCreateConstructor() {
  68. let hasConstructor = false;
  69. const paths = classState.path.get("body.body");
  70. for (const path of paths) {
  71. hasConstructor = path.equals("kind", "constructor");
  72. if (hasConstructor) break;
  73. }
  74. if (hasConstructor) return;
  75. let params, body;
  76. if (classState.isDerived) {
  77. const constructor = _core.template.expression.ast`
  78. (function () {
  79. super(...arguments);
  80. })
  81. `;
  82. params = constructor.params;
  83. body = constructor.body;
  84. } else {
  85. params = [];
  86. body = _core.types.blockStatement([]);
  87. }
  88. classState.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
  89. }
  90. function buildBody() {
  91. maybeCreateConstructor();
  92. pushBody();
  93. verifyConstructor();
  94. if (classState.userConstructor) {
  95. const {
  96. constructorBody,
  97. userConstructor,
  98. construct
  99. } = classState;
  100. constructorBody.body = constructorBody.body.concat(userConstructor.body.body);
  101. _core.types.inherits(construct, userConstructor);
  102. _core.types.inherits(constructorBody, userConstructor.body);
  103. }
  104. pushDescriptors();
  105. }
  106. function pushBody() {
  107. const classBodyPaths = classState.path.get("body.body");
  108. for (const path of classBodyPaths) {
  109. const node = path.node;
  110. if (path.isClassProperty()) {
  111. throw path.buildCodeFrameError("Missing class properties transform.");
  112. }
  113. if (node.decorators) {
  114. throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
  115. }
  116. if (_core.types.isClassMethod(node)) {
  117. const isConstructor = node.kind === "constructor";
  118. const replaceSupers = new _helperReplaceSupers.default({
  119. methodPath: path,
  120. objectRef: classState.classRef,
  121. superRef: classState.superName,
  122. constantSuper: assumptions.constantSuper,
  123. file: classState.file,
  124. refToPreserve: classState.classRef
  125. });
  126. replaceSupers.replace();
  127. const superReturns = [];
  128. path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  129. ReturnStatement(path) {
  130. if (!path.getFunctionParent().isArrowFunctionExpression()) {
  131. superReturns.push(path);
  132. }
  133. }
  134. }]));
  135. if (isConstructor) {
  136. pushConstructor(superReturns, node, path);
  137. } else {
  138. pushMethod(node, path);
  139. }
  140. }
  141. }
  142. }
  143. function pushDescriptors() {
  144. pushInheritsToBody();
  145. const {
  146. body
  147. } = classState;
  148. const props = {
  149. instance: null,
  150. static: null
  151. };
  152. for (const placement of ["static", "instance"]) {
  153. if (classState.methods[placement].list.length) {
  154. props[placement] = classState.methods[placement].list.map(desc => {
  155. const obj = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("key"), desc.key)]);
  156. for (const kind of ["get", "set", "value"]) {
  157. if (desc[kind] != null) {
  158. obj.properties.push(_core.types.objectProperty(_core.types.identifier(kind), desc[kind]));
  159. }
  160. }
  161. return obj;
  162. });
  163. }
  164. }
  165. if (props.instance || props.static) {
  166. let args = [_core.types.cloneNode(classState.classRef), props.instance ? _core.types.arrayExpression(props.instance) : _core.types.nullLiteral(), props.static ? _core.types.arrayExpression(props.static) : _core.types.nullLiteral()];
  167. let lastNonNullIndex = 0;
  168. for (let i = 0; i < args.length; i++) {
  169. if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
  170. }
  171. args = args.slice(0, lastNonNullIndex + 1);
  172. body.push(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("createClass"), args)));
  173. }
  174. }
  175. function wrapSuperCall(bareSuper, superRef, thisRef, body) {
  176. const bareSuperNode = bareSuper.node;
  177. let call;
  178. if (assumptions.superIsCallableConstructor) {
  179. bareSuperNode.arguments.unshift(_core.types.thisExpression());
  180. if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
  181. name: "arguments"
  182. })) {
  183. bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
  184. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
  185. } else {
  186. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
  187. }
  188. call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
  189. } else {
  190. call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments);
  191. }
  192. if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
  193. if (classState.superThises.length) {
  194. call = _core.types.assignmentExpression("=", thisRef(), call);
  195. }
  196. bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
  197. } else {
  198. bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
  199. }
  200. }
  201. function verifyConstructor() {
  202. if (!classState.isDerived) return;
  203. const path = classState.userConstructorPath;
  204. const body = path.get("body");
  205. path.traverse(findThisesVisitor);
  206. let thisRef = function () {
  207. const ref = path.scope.generateDeclaredUidIdentifier("this");
  208. thisRef = () => _core.types.cloneNode(ref);
  209. return ref;
  210. };
  211. for (const thisPath of classState.superThises) {
  212. const {
  213. node,
  214. parentPath
  215. } = thisPath;
  216. if (parentPath.isMemberExpression({
  217. object: node
  218. })) {
  219. thisPath.replaceWith(thisRef());
  220. continue;
  221. }
  222. thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
  223. }
  224. const bareSupers = new Set();
  225. path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  226. Super(path) {
  227. const {
  228. node,
  229. parentPath
  230. } = path;
  231. if (parentPath.isCallExpression({
  232. callee: node
  233. })) {
  234. bareSupers.add(parentPath);
  235. }
  236. }
  237. }]));
  238. let guaranteedSuperBeforeFinish = !!bareSupers.size;
  239. for (const bareSuper of bareSupers) {
  240. wrapSuperCall(bareSuper, classState.superName, thisRef, body);
  241. if (guaranteedSuperBeforeFinish) {
  242. bareSuper.find(function (parentPath) {
  243. if (parentPath === path) {
  244. return true;
  245. }
  246. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  247. guaranteedSuperBeforeFinish = false;
  248. return true;
  249. }
  250. });
  251. }
  252. }
  253. let wrapReturn;
  254. if (classState.isLoose) {
  255. wrapReturn = returnArg => {
  256. const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
  257. return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  258. };
  259. } else {
  260. wrapReturn = returnArg => _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
  261. }
  262. const bodyPaths = body.get("body");
  263. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  264. body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
  265. }
  266. for (const returnPath of classState.superReturns) {
  267. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  268. }
  269. }
  270. function pushMethod(node, path) {
  271. const scope = path ? path.scope : classState.scope;
  272. if (node.kind === "method") {
  273. if (processMethod(node, scope)) return;
  274. }
  275. const placement = node.static ? "static" : "instance";
  276. const methods = classState.methods[placement];
  277. const descKey = node.kind === "method" ? "value" : node.kind;
  278. const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
  279. let fn = _core.types.toExpression(node);
  280. if (_core.types.isStringLiteral(key)) {
  281. if (node.kind === "method") {
  282. fn = (0, _helperFunctionName.default)({
  283. id: key,
  284. node: node,
  285. scope
  286. });
  287. }
  288. } else {
  289. methods.hasComputed = true;
  290. }
  291. let descriptor;
  292. if (!methods.hasComputed && methods.map.has(key.value)) {
  293. descriptor = methods.map.get(key.value);
  294. descriptor[descKey] = fn;
  295. if (descKey === "value") {
  296. descriptor.get = null;
  297. descriptor.set = null;
  298. } else {
  299. descriptor.value = null;
  300. }
  301. } else {
  302. descriptor = {
  303. key: key,
  304. [descKey]: fn
  305. };
  306. methods.list.push(descriptor);
  307. if (!methods.hasComputed) {
  308. methods.map.set(key.value, descriptor);
  309. }
  310. }
  311. }
  312. function processMethod(node, scope) {
  313. if (assumptions.setClassMethods && !node.decorators) {
  314. let {
  315. classRef
  316. } = classState;
  317. if (!node.static) {
  318. insertProtoAliasOnce();
  319. classRef = classState.protoAlias;
  320. }
  321. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  322. let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
  323. _core.types.inherits(func, node);
  324. const key = _core.types.toComputedKey(node, node.key);
  325. if (_core.types.isStringLiteral(key)) {
  326. func = (0, _helperFunctionName.default)({
  327. node: func,
  328. id: key,
  329. scope
  330. });
  331. }
  332. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  333. _core.types.inheritsComments(expr, node);
  334. classState.body.push(expr);
  335. return true;
  336. }
  337. return false;
  338. }
  339. function insertProtoAliasOnce() {
  340. if (classState.protoAlias === null) {
  341. setState({
  342. protoAlias: classState.scope.generateUidIdentifier("proto")
  343. });
  344. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  345. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  346. classState.body.push(protoDeclaration);
  347. }
  348. }
  349. function pushConstructor(superReturns, method, path) {
  350. setState({
  351. userConstructorPath: path,
  352. userConstructor: method,
  353. hasConstructor: true,
  354. superReturns
  355. });
  356. const {
  357. construct
  358. } = classState;
  359. _core.types.inheritsComments(construct, method);
  360. construct.params = method.params;
  361. _core.types.inherits(construct.body, method.body);
  362. construct.body.directives = method.body.directives;
  363. pushConstructorToBody();
  364. }
  365. function pushConstructorToBody() {
  366. if (classState.pushedConstructor) return;
  367. classState.pushedConstructor = true;
  368. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  369. pushDescriptors();
  370. }
  371. classState.body.push(classState.construct);
  372. pushInheritsToBody();
  373. }
  374. function pushInheritsToBody() {
  375. if (!classState.isDerived || classState.pushedInherits) return;
  376. const superFnId = path.scope.generateUidIdentifier("super");
  377. setState({
  378. pushedInherits: true,
  379. superFnId
  380. });
  381. if (!assumptions.superIsCallableConstructor) {
  382. classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
  383. }
  384. classState.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core.types.cloneNode(classState.classRef), _core.types.cloneNode(classState.superName)])));
  385. }
  386. function setupClosureParamsArgs() {
  387. const {
  388. superName
  389. } = classState;
  390. const closureParams = [];
  391. const closureArgs = [];
  392. if (classState.isDerived) {
  393. let arg = _core.types.cloneNode(superName);
  394. if (classState.extendsNative) {
  395. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  396. (0, _helperAnnotateAsPure.default)(arg);
  397. }
  398. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  399. closureParams.push(param);
  400. closureArgs.push(arg);
  401. setState({
  402. superName: _core.types.cloneNode(param)
  403. });
  404. }
  405. return {
  406. closureParams,
  407. closureArgs
  408. };
  409. }
  410. function classTransformer(path, file, builtinClasses, isLoose) {
  411. setState({
  412. parent: path.parent,
  413. scope: path.scope,
  414. node: path.node,
  415. path,
  416. file,
  417. isLoose
  418. });
  419. setState({
  420. classId: classState.node.id,
  421. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  422. superName: classState.node.superClass,
  423. isDerived: !!classState.node.superClass,
  424. constructorBody: _core.types.blockStatement([])
  425. });
  426. setState({
  427. extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  428. });
  429. const {
  430. classRef,
  431. node,
  432. constructorBody
  433. } = classState;
  434. setState({
  435. construct: buildConstructor(classRef, constructorBody, node)
  436. });
  437. let {
  438. body
  439. } = classState;
  440. const {
  441. closureParams,
  442. closureArgs
  443. } = setupClosureParamsArgs();
  444. buildBody();
  445. if (!assumptions.noClassCalls) {
  446. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  447. }
  448. body = body.concat(classState.staticPropBody.map(fn => fn(_core.types.cloneNode(classState.classRef))));
  449. const isStrict = path.isInStrictMode();
  450. let constructorOnly = classState.classId && body.length === 1;
  451. if (constructorOnly && !isStrict) {
  452. for (const param of classState.construct.params) {
  453. if (!_core.types.isIdentifier(param)) {
  454. constructorOnly = false;
  455. break;
  456. }
  457. }
  458. }
  459. const directives = constructorOnly ? body[0].body.directives : [];
  460. if (!isStrict) {
  461. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  462. }
  463. if (constructorOnly) {
  464. return _core.types.toExpression(body[0]);
  465. }
  466. body.push(_core.types.returnStatement(_core.types.cloneNode(classState.classRef)));
  467. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  468. return _core.types.callExpression(container, closureArgs);
  469. }
  470. return classTransformer(path, file, builtinClasses, isLoose);
  471. }