referencer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /*
  2. Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. * Redistributions of source code must retain the above copyright
  6. notice, this list of conditions and the following disclaimer.
  7. * Redistributions in binary form must reproduce the above copyright
  8. notice, this list of conditions and the following disclaimer in the
  9. documentation and/or other materials provided with the distribution.
  10. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  11. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  14. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  15. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  16. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  17. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  18. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  19. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  20. */
  21. import estraverse from "estraverse";
  22. import esrecurse from "esrecurse";
  23. import Reference from "./reference.js";
  24. import Variable from "./variable.js";
  25. import PatternVisitor from "./pattern-visitor.js";
  26. import { Definition, ParameterDefinition } from "./definition.js";
  27. import { assert } from "./assert.js";
  28. const { Syntax } = estraverse;
  29. /**
  30. * Traverse identifier in pattern
  31. * @param {Object} options options
  32. * @param {pattern} rootPattern root pattern
  33. * @param {Refencer} referencer referencer
  34. * @param {callback} callback callback
  35. * @returns {void}
  36. */
  37. function traverseIdentifierInPattern(options, rootPattern, referencer, callback) {
  38. // Call the callback at left hand identifier nodes, and Collect right hand nodes.
  39. const visitor = new PatternVisitor(options, rootPattern, callback);
  40. visitor.visit(rootPattern);
  41. // Process the right hand nodes recursively.
  42. if (referencer !== null && referencer !== void 0) {
  43. visitor.rightHandNodes.forEach(referencer.visit, referencer);
  44. }
  45. }
  46. // Importing ImportDeclaration.
  47. // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
  48. // https://github.com/estree/estree/blob/master/es6.md#importdeclaration
  49. // FIXME: Now, we don't create module environment, because the context is
  50. // implementation dependent.
  51. /**
  52. * Visitor for import specifiers.
  53. */
  54. class Importer extends esrecurse.Visitor {
  55. constructor(declaration, referencer) {
  56. super(null, referencer.options);
  57. this.declaration = declaration;
  58. this.referencer = referencer;
  59. }
  60. visitImport(id, specifier) {
  61. this.referencer.visitPattern(id, pattern => {
  62. this.referencer.currentScope().__define(pattern,
  63. new Definition(
  64. Variable.ImportBinding,
  65. pattern,
  66. specifier,
  67. this.declaration,
  68. null,
  69. null
  70. ));
  71. });
  72. }
  73. ImportNamespaceSpecifier(node) {
  74. const local = (node.local || node.id);
  75. if (local) {
  76. this.visitImport(local, node);
  77. }
  78. }
  79. ImportDefaultSpecifier(node) {
  80. const local = (node.local || node.id);
  81. this.visitImport(local, node);
  82. }
  83. ImportSpecifier(node) {
  84. const local = (node.local || node.id);
  85. if (node.name) {
  86. this.visitImport(node.name, node);
  87. } else {
  88. this.visitImport(local, node);
  89. }
  90. }
  91. }
  92. /**
  93. * Referencing variables and creating bindings.
  94. */
  95. class Referencer extends esrecurse.Visitor {
  96. constructor(options, scopeManager) {
  97. super(null, options);
  98. this.options = options;
  99. this.scopeManager = scopeManager;
  100. this.parent = null;
  101. this.isInnerMethodDefinition = false;
  102. }
  103. currentScope() {
  104. return this.scopeManager.__currentScope;
  105. }
  106. close(node) {
  107. while (this.currentScope() && node === this.currentScope().block) {
  108. this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);
  109. }
  110. }
  111. pushInnerMethodDefinition(isInnerMethodDefinition) {
  112. const previous = this.isInnerMethodDefinition;
  113. this.isInnerMethodDefinition = isInnerMethodDefinition;
  114. return previous;
  115. }
  116. popInnerMethodDefinition(isInnerMethodDefinition) {
  117. this.isInnerMethodDefinition = isInnerMethodDefinition;
  118. }
  119. referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
  120. const scope = this.currentScope();
  121. assignments.forEach(assignment => {
  122. scope.__referencing(
  123. pattern,
  124. Reference.WRITE,
  125. assignment.right,
  126. maybeImplicitGlobal,
  127. pattern !== assignment.left,
  128. init
  129. );
  130. });
  131. }
  132. visitPattern(node, options, callback) {
  133. let visitPatternOptions = options;
  134. let visitPatternCallback = callback;
  135. if (typeof options === "function") {
  136. visitPatternCallback = options;
  137. visitPatternOptions = { processRightHandNodes: false };
  138. }
  139. traverseIdentifierInPattern(
  140. this.options,
  141. node,
  142. visitPatternOptions.processRightHandNodes ? this : null,
  143. visitPatternCallback
  144. );
  145. }
  146. visitFunction(node) {
  147. let i, iz;
  148. // FunctionDeclaration name is defined in upper scope
  149. // NOTE: Not referring variableScope. It is intended.
  150. // Since
  151. // in ES5, FunctionDeclaration should be in FunctionBody.
  152. // in ES6, FunctionDeclaration should be block scoped.
  153. if (node.type === Syntax.FunctionDeclaration) {
  154. // id is defined in upper scope
  155. this.currentScope().__define(node.id,
  156. new Definition(
  157. Variable.FunctionName,
  158. node.id,
  159. node,
  160. null,
  161. null,
  162. null
  163. ));
  164. }
  165. // FunctionExpression with name creates its special scope;
  166. // FunctionExpressionNameScope.
  167. if (node.type === Syntax.FunctionExpression && node.id) {
  168. this.scopeManager.__nestFunctionExpressionNameScope(node);
  169. }
  170. // Consider this function is in the MethodDefinition.
  171. this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);
  172. const that = this;
  173. /**
  174. * Visit pattern callback
  175. * @param {pattern} pattern pattern
  176. * @param {Object} info info
  177. * @returns {void}
  178. */
  179. function visitPatternCallback(pattern, info) {
  180. that.currentScope().__define(pattern,
  181. new ParameterDefinition(
  182. pattern,
  183. node,
  184. i,
  185. info.rest
  186. ));
  187. that.referencingDefaultValue(pattern, info.assignments, null, true);
  188. }
  189. // Process parameter declarations.
  190. for (i = 0, iz = node.params.length; i < iz; ++i) {
  191. this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback);
  192. }
  193. // if there's a rest argument, add that
  194. if (node.rest) {
  195. this.visitPattern({
  196. type: "RestElement",
  197. argument: node.rest
  198. }, pattern => {
  199. this.currentScope().__define(pattern,
  200. new ParameterDefinition(
  201. pattern,
  202. node,
  203. node.params.length,
  204. true
  205. ));
  206. });
  207. }
  208. // In TypeScript there are a number of function-like constructs which have no body,
  209. // so check it exists before traversing
  210. if (node.body) {
  211. // Skip BlockStatement to prevent creating BlockStatement scope.
  212. if (node.body.type === Syntax.BlockStatement) {
  213. this.visitChildren(node.body);
  214. } else {
  215. this.visit(node.body);
  216. }
  217. }
  218. this.close(node);
  219. }
  220. visitClass(node) {
  221. if (node.type === Syntax.ClassDeclaration) {
  222. this.currentScope().__define(node.id,
  223. new Definition(
  224. Variable.ClassName,
  225. node.id,
  226. node,
  227. null,
  228. null,
  229. null
  230. ));
  231. }
  232. this.scopeManager.__nestClassScope(node);
  233. if (node.id) {
  234. this.currentScope().__define(node.id,
  235. new Definition(
  236. Variable.ClassName,
  237. node.id,
  238. node
  239. ));
  240. }
  241. this.visit(node.superClass);
  242. this.visit(node.body);
  243. this.close(node);
  244. }
  245. visitProperty(node) {
  246. let previous;
  247. if (node.computed) {
  248. this.visit(node.key);
  249. }
  250. const isMethodDefinition = node.type === Syntax.MethodDefinition;
  251. if (isMethodDefinition) {
  252. previous = this.pushInnerMethodDefinition(true);
  253. }
  254. this.visit(node.value);
  255. if (isMethodDefinition) {
  256. this.popInnerMethodDefinition(previous);
  257. }
  258. }
  259. visitForIn(node) {
  260. if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") {
  261. this.scopeManager.__nestForScope(node);
  262. }
  263. if (node.left.type === Syntax.VariableDeclaration) {
  264. this.visit(node.left);
  265. this.visitPattern(node.left.declarations[0].id, pattern => {
  266. this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);
  267. });
  268. } else {
  269. this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {
  270. let maybeImplicitGlobal = null;
  271. if (!this.currentScope().isStrict) {
  272. maybeImplicitGlobal = {
  273. pattern,
  274. node
  275. };
  276. }
  277. this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
  278. this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false);
  279. });
  280. }
  281. this.visit(node.right);
  282. this.visit(node.body);
  283. this.close(node);
  284. }
  285. visitVariableDeclaration(variableTargetScope, type, node, index) {
  286. const decl = node.declarations[index];
  287. const init = decl.init;
  288. this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => {
  289. variableTargetScope.__define(
  290. pattern,
  291. new Definition(
  292. type,
  293. pattern,
  294. decl,
  295. node,
  296. index,
  297. node.kind
  298. )
  299. );
  300. this.referencingDefaultValue(pattern, info.assignments, null, true);
  301. if (init) {
  302. this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true);
  303. }
  304. });
  305. }
  306. AssignmentExpression(node) {
  307. if (PatternVisitor.isPattern(node.left)) {
  308. if (node.operator === "=") {
  309. this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {
  310. let maybeImplicitGlobal = null;
  311. if (!this.currentScope().isStrict) {
  312. maybeImplicitGlobal = {
  313. pattern,
  314. node
  315. };
  316. }
  317. this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
  318. this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);
  319. });
  320. } else {
  321. this.currentScope().__referencing(node.left, Reference.RW, node.right);
  322. }
  323. } else {
  324. this.visit(node.left);
  325. }
  326. this.visit(node.right);
  327. }
  328. CatchClause(node) {
  329. this.scopeManager.__nestCatchScope(node);
  330. this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => {
  331. this.currentScope().__define(pattern,
  332. new Definition(
  333. Variable.CatchClause,
  334. pattern,
  335. node,
  336. null,
  337. null,
  338. null
  339. ));
  340. this.referencingDefaultValue(pattern, info.assignments, null, true);
  341. });
  342. this.visit(node.body);
  343. this.close(node);
  344. }
  345. Program(node) {
  346. this.scopeManager.__nestGlobalScope(node);
  347. if (this.scopeManager.isGlobalReturn()) {
  348. // Force strictness of GlobalScope to false when using node.js scope.
  349. this.currentScope().isStrict = false;
  350. this.scopeManager.__nestFunctionScope(node, false);
  351. }
  352. if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
  353. this.scopeManager.__nestModuleScope(node);
  354. }
  355. if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) {
  356. this.currentScope().isStrict = true;
  357. }
  358. this.visitChildren(node);
  359. this.close(node);
  360. }
  361. Identifier(node) {
  362. this.currentScope().__referencing(node);
  363. }
  364. // eslint-disable-next-line class-methods-use-this -- Desired as instance method
  365. PrivateIdentifier() {
  366. // Do nothing.
  367. }
  368. UpdateExpression(node) {
  369. if (PatternVisitor.isPattern(node.argument)) {
  370. this.currentScope().__referencing(node.argument, Reference.RW, null);
  371. } else {
  372. this.visitChildren(node);
  373. }
  374. }
  375. MemberExpression(node) {
  376. this.visit(node.object);
  377. if (node.computed) {
  378. this.visit(node.property);
  379. }
  380. }
  381. Property(node) {
  382. this.visitProperty(node);
  383. }
  384. PropertyDefinition(node) {
  385. const { computed, key, value } = node;
  386. if (computed) {
  387. this.visit(key);
  388. }
  389. if (value) {
  390. this.scopeManager.__nestClassFieldInitializerScope(value);
  391. this.visit(value);
  392. this.close(value);
  393. }
  394. }
  395. StaticBlock(node) {
  396. this.scopeManager.__nestClassStaticBlockScope(node);
  397. this.visitChildren(node);
  398. this.close(node);
  399. }
  400. MethodDefinition(node) {
  401. this.visitProperty(node);
  402. }
  403. BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method
  404. ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method
  405. LabeledStatement(node) {
  406. this.visit(node.body);
  407. }
  408. ForStatement(node) {
  409. // Create ForStatement declaration.
  410. // NOTE: In ES6, ForStatement dynamically generates
  411. // per iteration environment. However, escope is
  412. // a static analyzer, we only generate one scope for ForStatement.
  413. if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") {
  414. this.scopeManager.__nestForScope(node);
  415. }
  416. this.visitChildren(node);
  417. this.close(node);
  418. }
  419. ClassExpression(node) {
  420. this.visitClass(node);
  421. }
  422. ClassDeclaration(node) {
  423. this.visitClass(node);
  424. }
  425. CallExpression(node) {
  426. // Check this is direct call to eval
  427. if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") {
  428. // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
  429. // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
  430. this.currentScope().variableScope.__detectEval();
  431. }
  432. this.visitChildren(node);
  433. }
  434. BlockStatement(node) {
  435. if (this.scopeManager.__isES6()) {
  436. this.scopeManager.__nestBlockScope(node);
  437. }
  438. this.visitChildren(node);
  439. this.close(node);
  440. }
  441. ThisExpression() {
  442. this.currentScope().variableScope.__detectThis();
  443. }
  444. WithStatement(node) {
  445. this.visit(node.object);
  446. // Then nest scope for WithStatement.
  447. this.scopeManager.__nestWithScope(node);
  448. this.visit(node.body);
  449. this.close(node);
  450. }
  451. VariableDeclaration(node) {
  452. const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope();
  453. for (let i = 0, iz = node.declarations.length; i < iz; ++i) {
  454. const decl = node.declarations[i];
  455. this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i);
  456. if (decl.init) {
  457. this.visit(decl.init);
  458. }
  459. }
  460. }
  461. // sec 13.11.8
  462. SwitchStatement(node) {
  463. this.visit(node.discriminant);
  464. if (this.scopeManager.__isES6()) {
  465. this.scopeManager.__nestSwitchScope(node);
  466. }
  467. for (let i = 0, iz = node.cases.length; i < iz; ++i) {
  468. this.visit(node.cases[i]);
  469. }
  470. this.close(node);
  471. }
  472. FunctionDeclaration(node) {
  473. this.visitFunction(node);
  474. }
  475. FunctionExpression(node) {
  476. this.visitFunction(node);
  477. }
  478. ForOfStatement(node) {
  479. this.visitForIn(node);
  480. }
  481. ForInStatement(node) {
  482. this.visitForIn(node);
  483. }
  484. ArrowFunctionExpression(node) {
  485. this.visitFunction(node);
  486. }
  487. ImportDeclaration(node) {
  488. assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context.");
  489. const importer = new Importer(node, this);
  490. importer.visit(node);
  491. }
  492. visitExportDeclaration(node) {
  493. if (node.source) {
  494. return;
  495. }
  496. if (node.declaration) {
  497. this.visit(node.declaration);
  498. return;
  499. }
  500. this.visitChildren(node);
  501. }
  502. // TODO: ExportDeclaration doesn't exist. for bc?
  503. ExportDeclaration(node) {
  504. this.visitExportDeclaration(node);
  505. }
  506. ExportAllDeclaration(node) {
  507. this.visitExportDeclaration(node);
  508. }
  509. ExportDefaultDeclaration(node) {
  510. this.visitExportDeclaration(node);
  511. }
  512. ExportNamedDeclaration(node) {
  513. this.visitExportDeclaration(node);
  514. }
  515. ExportSpecifier(node) {
  516. // TODO: `node.id` doesn't exist. for bc?
  517. const local = (node.id || node.local);
  518. this.visit(local);
  519. }
  520. MetaProperty() { // eslint-disable-line class-methods-use-this -- Desired as instance method
  521. // do nothing.
  522. }
  523. }
  524. export default Referencer;
  525. /* vim: set sw=4 ts=4 et tw=80 : */