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.

722 lines
20 KiB

  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _tdz = require("./tdz");
  8. var _core = require("@babel/core");
  9. const DONE = new WeakSet();
  10. var _default = (0, _helperPluginUtils.declare)((api, opts) => {
  11. api.assertVersion(7);
  12. const {
  13. throwIfClosureRequired = false,
  14. tdz: tdzEnabled = false
  15. } = opts;
  16. if (typeof throwIfClosureRequired !== "boolean") {
  17. throw new Error(`.throwIfClosureRequired must be a boolean, or undefined`);
  18. }
  19. if (typeof tdzEnabled !== "boolean") {
  20. throw new Error(`.tdz must be a boolean, or undefined`);
  21. }
  22. return {
  23. name: "transform-block-scoping",
  24. visitor: {
  25. VariableDeclaration(path) {
  26. const {
  27. node,
  28. parent,
  29. scope
  30. } = path;
  31. if (!isBlockScoped(node)) return;
  32. convertBlockScopedToVar(path, null, parent, scope, true);
  33. if (node._tdzThis) {
  34. const nodes = [node];
  35. for (let i = 0; i < node.declarations.length; i++) {
  36. const decl = node.declarations[i];
  37. const assign = _core.types.assignmentExpression("=", _core.types.cloneNode(decl.id), decl.init || scope.buildUndefinedNode());
  38. assign._ignoreBlockScopingTDZ = true;
  39. nodes.push(_core.types.expressionStatement(assign));
  40. decl.init = this.addHelper("temporalUndefined");
  41. }
  42. node._blockHoist = 2;
  43. if (path.isCompletionRecord()) {
  44. nodes.push(_core.types.expressionStatement(scope.buildUndefinedNode()));
  45. }
  46. path.replaceWithMultiple(nodes);
  47. }
  48. },
  49. Loop(path, state) {
  50. const {
  51. parent,
  52. scope
  53. } = path;
  54. path.ensureBlock();
  55. const blockScoping = new BlockScoping(path, path.get("body"), parent, scope, throwIfClosureRequired, tdzEnabled, state);
  56. const replace = blockScoping.run();
  57. if (replace) path.replaceWith(replace);
  58. },
  59. CatchClause(path, state) {
  60. const {
  61. parent,
  62. scope
  63. } = path;
  64. const blockScoping = new BlockScoping(null, path.get("body"), parent, scope, throwIfClosureRequired, tdzEnabled, state);
  65. blockScoping.run();
  66. },
  67. "BlockStatement|SwitchStatement|Program"(path, state) {
  68. if (!ignoreBlock(path)) {
  69. const blockScoping = new BlockScoping(null, path, path.parent, path.scope, throwIfClosureRequired, tdzEnabled, state);
  70. blockScoping.run();
  71. }
  72. }
  73. }
  74. };
  75. });
  76. exports.default = _default;
  77. function ignoreBlock(path) {
  78. return _core.types.isLoop(path.parent) || _core.types.isCatchClause(path.parent);
  79. }
  80. const buildRetCheck = (0, _core.template)(`
  81. if (typeof RETURN === "object") return RETURN.v;
  82. `);
  83. function isBlockScoped(node) {
  84. if (!_core.types.isVariableDeclaration(node)) return false;
  85. if (node[_core.types.BLOCK_SCOPED_SYMBOL]) return true;
  86. if (node.kind !== "let" && node.kind !== "const") return false;
  87. return true;
  88. }
  89. function isInLoop(path) {
  90. const loopOrFunctionParent = path.find(path => path.isLoop() || path.isFunction());
  91. return loopOrFunctionParent == null ? void 0 : loopOrFunctionParent.isLoop();
  92. }
  93. function convertBlockScopedToVar(path, node, parent, scope, moveBindingsToParent = false) {
  94. if (!node) {
  95. node = path.node;
  96. }
  97. if (isInLoop(path) && !_core.types.isFor(parent)) {
  98. for (let i = 0; i < node.declarations.length; i++) {
  99. const declar = node.declarations[i];
  100. declar.init = declar.init || scope.buildUndefinedNode();
  101. }
  102. }
  103. node[_core.types.BLOCK_SCOPED_SYMBOL] = true;
  104. node.kind = "var";
  105. if (moveBindingsToParent) {
  106. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  107. for (const name of Object.keys(path.getBindingIdentifiers())) {
  108. const binding = scope.getOwnBinding(name);
  109. if (binding) binding.kind = "var";
  110. scope.moveBindingTo(name, parentScope);
  111. }
  112. }
  113. }
  114. function isVar(node) {
  115. return _core.types.isVariableDeclaration(node, {
  116. kind: "var"
  117. }) && !isBlockScoped(node);
  118. }
  119. const letReferenceBlockVisitor = _core.traverse.visitors.merge([{
  120. Loop: {
  121. enter(path, state) {
  122. state.loopDepth++;
  123. },
  124. exit(path, state) {
  125. state.loopDepth--;
  126. }
  127. },
  128. Function(path, state) {
  129. if (state.loopDepth > 0) {
  130. path.traverse(letReferenceFunctionVisitor, state);
  131. } else {
  132. path.traverse(_tdz.visitor, state);
  133. }
  134. return path.skip();
  135. }
  136. }, _tdz.visitor]);
  137. const letReferenceFunctionVisitor = _core.traverse.visitors.merge([{
  138. ReferencedIdentifier(path, state) {
  139. const ref = state.letReferences.get(path.node.name);
  140. if (!ref) return;
  141. const localBinding = path.scope.getBindingIdentifier(path.node.name);
  142. if (localBinding && localBinding !== ref) return;
  143. state.closurify = true;
  144. }
  145. }, _tdz.visitor]);
  146. const hoistVarDeclarationsVisitor = {
  147. enter(path, self) {
  148. const {
  149. node,
  150. parent
  151. } = path;
  152. if (path.isForStatement()) {
  153. if (isVar(node.init, node)) {
  154. const nodes = self.pushDeclar(node.init);
  155. if (nodes.length === 1) {
  156. node.init = nodes[0];
  157. } else {
  158. node.init = _core.types.sequenceExpression(nodes);
  159. }
  160. }
  161. } else if (path.isFor()) {
  162. if (isVar(node.left, node)) {
  163. self.pushDeclar(node.left);
  164. node.left = node.left.declarations[0].id;
  165. }
  166. } else if (isVar(node, parent)) {
  167. path.replaceWithMultiple(self.pushDeclar(node).map(expr => _core.types.expressionStatement(expr)));
  168. } else if (path.isFunction()) {
  169. return path.skip();
  170. }
  171. }
  172. };
  173. const loopLabelVisitor = {
  174. LabeledStatement({
  175. node
  176. }, state) {
  177. state.innerLabels.push(node.label.name);
  178. }
  179. };
  180. const continuationVisitor = {
  181. enter(path, state) {
  182. if (path.isAssignmentExpression() || path.isUpdateExpression()) {
  183. for (const name of Object.keys(path.getBindingIdentifiers())) {
  184. if (state.outsideReferences.get(name) !== path.scope.getBindingIdentifier(name)) {
  185. continue;
  186. }
  187. state.reassignments[name] = true;
  188. }
  189. } else if (path.isReturnStatement()) {
  190. state.returnStatements.push(path);
  191. }
  192. }
  193. };
  194. function loopNodeTo(node) {
  195. if (_core.types.isBreakStatement(node)) {
  196. return "break";
  197. } else if (_core.types.isContinueStatement(node)) {
  198. return "continue";
  199. }
  200. }
  201. const loopVisitor = {
  202. Loop(path, state) {
  203. const oldIgnoreLabeless = state.ignoreLabeless;
  204. state.ignoreLabeless = true;
  205. path.traverse(loopVisitor, state);
  206. state.ignoreLabeless = oldIgnoreLabeless;
  207. path.skip();
  208. },
  209. Function(path) {
  210. path.skip();
  211. },
  212. SwitchCase(path, state) {
  213. const oldInSwitchCase = state.inSwitchCase;
  214. state.inSwitchCase = true;
  215. path.traverse(loopVisitor, state);
  216. state.inSwitchCase = oldInSwitchCase;
  217. path.skip();
  218. },
  219. "BreakStatement|ContinueStatement|ReturnStatement"(path, state) {
  220. const {
  221. node,
  222. scope
  223. } = path;
  224. if (node[this.LOOP_IGNORE]) return;
  225. let replace;
  226. let loopText = loopNodeTo(node);
  227. if (loopText) {
  228. if (node.label) {
  229. if (state.innerLabels.indexOf(node.label.name) >= 0) {
  230. return;
  231. }
  232. loopText = `${loopText}|${node.label.name}`;
  233. } else {
  234. if (state.ignoreLabeless) return;
  235. if (_core.types.isBreakStatement(node) && state.inSwitchCase) return;
  236. }
  237. state.hasBreakContinue = true;
  238. state.map[loopText] = node;
  239. replace = _core.types.stringLiteral(loopText);
  240. }
  241. if (path.isReturnStatement()) {
  242. state.hasReturn = true;
  243. replace = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("v"), node.argument || scope.buildUndefinedNode())]);
  244. }
  245. if (replace) {
  246. replace = _core.types.returnStatement(replace);
  247. replace[this.LOOP_IGNORE] = true;
  248. path.skip();
  249. path.replaceWith(_core.types.inherits(replace, node));
  250. }
  251. }
  252. };
  253. function isStrict(path) {
  254. return !!path.find(({
  255. node
  256. }) => {
  257. if (_core.types.isProgram(node)) {
  258. if (node.sourceType === "module") return true;
  259. } else if (!_core.types.isBlockStatement(node)) return false;
  260. return node.directives.some(directive => directive.value.value === "use strict");
  261. });
  262. }
  263. class BlockScoping {
  264. constructor(loopPath, blockPath, parent, scope, throwIfClosureRequired, tdzEnabled, state) {
  265. this.parent = parent;
  266. this.scope = scope;
  267. this.state = state;
  268. this.throwIfClosureRequired = throwIfClosureRequired;
  269. this.tdzEnabled = tdzEnabled;
  270. this.blockPath = blockPath;
  271. this.block = blockPath.node;
  272. this.outsideLetReferences = new Map();
  273. this.hasLetReferences = false;
  274. this.letReferences = new Map();
  275. this.body = [];
  276. if (loopPath) {
  277. this.loopParent = loopPath.parent;
  278. this.loopLabel = _core.types.isLabeledStatement(this.loopParent) && this.loopParent.label;
  279. this.loopPath = loopPath;
  280. this.loop = loopPath.node;
  281. }
  282. }
  283. run() {
  284. const block = this.block;
  285. if (DONE.has(block)) return;
  286. DONE.add(block);
  287. const needsClosure = this.getLetReferences();
  288. this.checkConstants();
  289. if (_core.types.isFunction(this.parent) || _core.types.isProgram(this.block)) {
  290. this.updateScopeInfo();
  291. return;
  292. }
  293. if (!this.hasLetReferences) return;
  294. if (needsClosure) {
  295. this.wrapClosure();
  296. } else {
  297. this.remap();
  298. }
  299. this.updateScopeInfo(needsClosure);
  300. if (this.loopLabel && !_core.types.isLabeledStatement(this.loopParent)) {
  301. return _core.types.labeledStatement(this.loopLabel, this.loop);
  302. }
  303. }
  304. checkConstants() {
  305. const scope = this.scope;
  306. const state = this.state;
  307. for (const name of Object.keys(scope.bindings)) {
  308. const binding = scope.bindings[name];
  309. if (binding.kind !== "const") continue;
  310. for (const violation of binding.constantViolations) {
  311. const readOnlyError = state.addHelper("readOnlyError");
  312. const throwNode = _core.types.callExpression(readOnlyError, [_core.types.stringLiteral(name)]);
  313. if (violation.isAssignmentExpression()) {
  314. violation.get("right").replaceWith(_core.types.sequenceExpression([throwNode, violation.get("right").node]));
  315. } else if (violation.isUpdateExpression()) {
  316. violation.replaceWith(_core.types.sequenceExpression([throwNode, violation.node]));
  317. } else if (violation.isForXStatement()) {
  318. violation.ensureBlock();
  319. violation.node.body.body.unshift(_core.types.expressionStatement(throwNode));
  320. }
  321. }
  322. }
  323. }
  324. updateScopeInfo(wrappedInClosure) {
  325. const blockScope = this.blockPath.scope;
  326. const parentScope = blockScope.getFunctionParent() || blockScope.getProgramParent();
  327. const letRefs = this.letReferences;
  328. for (const key of letRefs.keys()) {
  329. const ref = letRefs.get(key);
  330. const binding = blockScope.getBinding(ref.name);
  331. if (!binding) continue;
  332. if (binding.kind === "let" || binding.kind === "const") {
  333. binding.kind = "var";
  334. if (wrappedInClosure) {
  335. if (blockScope.hasOwnBinding(ref.name)) {
  336. blockScope.removeBinding(ref.name);
  337. }
  338. } else {
  339. blockScope.moveBindingTo(ref.name, parentScope);
  340. }
  341. }
  342. }
  343. }
  344. remap() {
  345. const letRefs = this.letReferences;
  346. const outsideLetRefs = this.outsideLetReferences;
  347. const scope = this.scope;
  348. const blockPathScope = this.blockPath.scope;
  349. for (const key of letRefs.keys()) {
  350. const ref = letRefs.get(key);
  351. if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
  352. const binding = scope.getOwnBinding(key);
  353. if (binding) {
  354. const parentBinding = scope.parent.getOwnBinding(key);
  355. if (binding.kind === "hoisted" && !binding.path.node.async && !binding.path.node.generator && (!parentBinding || isVar(parentBinding.path.parent)) && !isStrict(binding.path.parentPath)) {
  356. continue;
  357. }
  358. scope.rename(ref.name);
  359. }
  360. if (blockPathScope.hasOwnBinding(key)) {
  361. blockPathScope.rename(ref.name);
  362. }
  363. }
  364. }
  365. for (const key of outsideLetRefs.keys()) {
  366. const ref = letRefs.get(key);
  367. if (isInLoop(this.blockPath) && blockPathScope.hasOwnBinding(key)) {
  368. blockPathScope.rename(ref.name);
  369. }
  370. }
  371. }
  372. wrapClosure() {
  373. if (this.throwIfClosureRequired) {
  374. throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired).");
  375. }
  376. const block = this.block;
  377. const outsideRefs = this.outsideLetReferences;
  378. if (this.loop) {
  379. for (const name of Array.from(outsideRefs.keys())) {
  380. const id = outsideRefs.get(name);
  381. if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) {
  382. outsideRefs.delete(id.name);
  383. this.letReferences.delete(id.name);
  384. this.scope.rename(id.name);
  385. this.letReferences.set(id.name, id);
  386. outsideRefs.set(id.name, id);
  387. }
  388. }
  389. }
  390. this.has = this.checkLoop();
  391. this.hoistVarDeclarations();
  392. const args = Array.from(outsideRefs.values(), node => _core.types.cloneNode(node));
  393. const params = args.map(id => _core.types.cloneNode(id));
  394. const isSwitch = this.blockPath.isSwitchStatement();
  395. const fn = _core.types.functionExpression(null, params, _core.types.blockStatement(isSwitch ? [block] : block.body));
  396. this.addContinuations(fn);
  397. let call = _core.types.callExpression(_core.types.nullLiteral(), args);
  398. let basePath = ".callee";
  399. const hasYield = _core.traverse.hasType(fn.body, "YieldExpression", _core.types.FUNCTION_TYPES);
  400. if (hasYield) {
  401. fn.generator = true;
  402. call = _core.types.yieldExpression(call, true);
  403. basePath = ".argument" + basePath;
  404. }
  405. const hasAsync = _core.traverse.hasType(fn.body, "AwaitExpression", _core.types.FUNCTION_TYPES);
  406. if (hasAsync) {
  407. fn.async = true;
  408. call = _core.types.awaitExpression(call);
  409. basePath = ".argument" + basePath;
  410. }
  411. let placeholderPath;
  412. let index;
  413. if (this.has.hasReturn || this.has.hasBreakContinue) {
  414. const ret = this.scope.generateUid("ret");
  415. this.body.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(ret), call)]));
  416. placeholderPath = "declarations.0.init" + basePath;
  417. index = this.body.length - 1;
  418. this.buildHas(ret);
  419. } else {
  420. this.body.push(_core.types.expressionStatement(call));
  421. placeholderPath = "expression" + basePath;
  422. index = this.body.length - 1;
  423. }
  424. let callPath;
  425. if (isSwitch) {
  426. const {
  427. parentPath,
  428. listKey,
  429. key
  430. } = this.blockPath;
  431. this.blockPath.replaceWithMultiple(this.body);
  432. callPath = parentPath.get(listKey)[key + index];
  433. } else {
  434. block.body = this.body;
  435. callPath = this.blockPath.get("body")[index];
  436. }
  437. const placeholder = callPath.get(placeholderPath);
  438. let fnPath;
  439. if (this.loop) {
  440. const loopId = this.scope.generateUid("loop");
  441. const p = this.loopPath.insertBefore(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(loopId), fn)]));
  442. placeholder.replaceWith(_core.types.identifier(loopId));
  443. fnPath = p[0].get("declarations.0.init");
  444. } else {
  445. placeholder.replaceWith(fn);
  446. fnPath = placeholder;
  447. }
  448. fnPath.unwrapFunctionEnvironment();
  449. }
  450. addContinuations(fn) {
  451. const state = {
  452. reassignments: {},
  453. returnStatements: [],
  454. outsideReferences: this.outsideLetReferences
  455. };
  456. this.scope.traverse(fn, continuationVisitor, state);
  457. for (let i = 0; i < fn.params.length; i++) {
  458. const param = fn.params[i];
  459. if (!state.reassignments[param.name]) continue;
  460. const paramName = param.name;
  461. const newParamName = this.scope.generateUid(param.name);
  462. fn.params[i] = _core.types.identifier(newParamName);
  463. this.scope.rename(paramName, newParamName, fn);
  464. state.returnStatements.forEach(returnStatement => {
  465. returnStatement.insertBefore(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.identifier(paramName), _core.types.identifier(newParamName))));
  466. });
  467. fn.body.body.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.identifier(paramName), _core.types.identifier(newParamName))));
  468. }
  469. }
  470. getLetReferences() {
  471. const block = this.block;
  472. let declarators = [];
  473. if (this.loop) {
  474. const init = this.loop.left || this.loop.init;
  475. if (isBlockScoped(init)) {
  476. declarators.push(init);
  477. const names = _core.types.getBindingIdentifiers(init);
  478. for (const name of Object.keys(names)) {
  479. this.outsideLetReferences.set(name, names[name]);
  480. }
  481. }
  482. }
  483. const addDeclarationsFromChild = (path, node) => {
  484. node = node || path.node;
  485. if (_core.types.isClassDeclaration(node) || _core.types.isFunctionDeclaration(node) || isBlockScoped(node)) {
  486. if (isBlockScoped(node)) {
  487. convertBlockScopedToVar(path, node, block, this.scope);
  488. }
  489. declarators = declarators.concat(node.declarations || node);
  490. }
  491. if (_core.types.isLabeledStatement(node)) {
  492. addDeclarationsFromChild(path.get("body"), node.body);
  493. }
  494. };
  495. if (block.body) {
  496. const declarPaths = this.blockPath.get("body");
  497. for (let i = 0; i < block.body.length; i++) {
  498. addDeclarationsFromChild(declarPaths[i]);
  499. }
  500. }
  501. if (block.cases) {
  502. const declarPaths = this.blockPath.get("cases");
  503. for (let i = 0; i < block.cases.length; i++) {
  504. const consequents = block.cases[i].consequent;
  505. for (let j = 0; j < consequents.length; j++) {
  506. const declar = consequents[j];
  507. addDeclarationsFromChild(declarPaths[i], declar);
  508. }
  509. }
  510. }
  511. for (let i = 0; i < declarators.length; i++) {
  512. const declar = declarators[i];
  513. const keys = _core.types.getBindingIdentifiers(declar, false, true);
  514. for (const key of Object.keys(keys)) {
  515. this.letReferences.set(key, keys[key]);
  516. }
  517. this.hasLetReferences = true;
  518. }
  519. if (!this.hasLetReferences) return;
  520. const state = {
  521. letReferences: this.letReferences,
  522. closurify: false,
  523. loopDepth: 0,
  524. tdzEnabled: this.tdzEnabled,
  525. addHelper: name => this.state.addHelper(name)
  526. };
  527. if (isInLoop(this.blockPath)) {
  528. state.loopDepth++;
  529. }
  530. this.blockPath.traverse(letReferenceBlockVisitor, state);
  531. return state.closurify;
  532. }
  533. checkLoop() {
  534. const state = {
  535. hasBreakContinue: false,
  536. ignoreLabeless: false,
  537. inSwitchCase: false,
  538. innerLabels: [],
  539. hasReturn: false,
  540. isLoop: !!this.loop,
  541. map: {},
  542. LOOP_IGNORE: Symbol()
  543. };
  544. this.blockPath.traverse(loopLabelVisitor, state);
  545. this.blockPath.traverse(loopVisitor, state);
  546. return state;
  547. }
  548. hoistVarDeclarations() {
  549. this.blockPath.traverse(hoistVarDeclarationsVisitor, this);
  550. }
  551. pushDeclar(node) {
  552. const declars = [];
  553. const names = _core.types.getBindingIdentifiers(node);
  554. for (const name of Object.keys(names)) {
  555. declars.push(_core.types.variableDeclarator(names[name]));
  556. }
  557. this.body.push(_core.types.variableDeclaration(node.kind, declars));
  558. const replace = [];
  559. for (let i = 0; i < node.declarations.length; i++) {
  560. const declar = node.declarations[i];
  561. if (!declar.init) continue;
  562. const expr = _core.types.assignmentExpression("=", _core.types.cloneNode(declar.id), _core.types.cloneNode(declar.init));
  563. replace.push(_core.types.inherits(expr, declar));
  564. }
  565. return replace;
  566. }
  567. buildHas(ret) {
  568. const body = this.body;
  569. const has = this.has;
  570. if (has.hasBreakContinue) {
  571. for (const key of Object.keys(has.map)) {
  572. body.push(_core.types.ifStatement(_core.types.binaryExpression("===", _core.types.identifier(ret), _core.types.stringLiteral(key)), has.map[key]));
  573. }
  574. }
  575. if (has.hasReturn) {
  576. body.push(buildRetCheck({
  577. RETURN: _core.types.identifier(ret)
  578. }));
  579. }
  580. }
  581. }