referencer.js 18 KB

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