scope.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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 Reference = require("./reference");
  26. const Variable = require("./variable");
  27. const Definition = require("./definition").Definition;
  28. const assert = require("assert");
  29. /**
  30. * Test if scope is struct
  31. * @param {Scope} scope - scope
  32. * @param {Block} block - block
  33. * @param {boolean} isMethodDefinition - is method definition
  34. * @param {boolean} useDirective - use directive
  35. * @returns {boolean} is strict scope
  36. */
  37. function isStrictScope(scope, block, isMethodDefinition, useDirective) {
  38. let body;
  39. // When upper scope is exists and strict, inner scope is also strict.
  40. if (scope.upper && scope.upper.isStrict) {
  41. return true;
  42. }
  43. if (isMethodDefinition) {
  44. return true;
  45. }
  46. if (scope.type === "class" || scope.type === "module") {
  47. return true;
  48. }
  49. if (scope.type === "block" || scope.type === "switch") {
  50. return false;
  51. }
  52. if (scope.type === "function") {
  53. if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) {
  54. return false;
  55. }
  56. if (block.type === Syntax.Program) {
  57. body = block;
  58. } else {
  59. body = block.body;
  60. }
  61. if (!body) {
  62. return false;
  63. }
  64. } else if (scope.type === "global") {
  65. body = block;
  66. } else {
  67. return false;
  68. }
  69. // Search 'use strict' directive.
  70. if (useDirective) {
  71. for (let i = 0, iz = body.body.length; i < iz; ++i) {
  72. const stmt = body.body[i];
  73. if (stmt.type !== Syntax.DirectiveStatement) {
  74. break;
  75. }
  76. if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") {
  77. return true;
  78. }
  79. }
  80. } else {
  81. for (let i = 0, iz = body.body.length; i < iz; ++i) {
  82. const stmt = body.body[i];
  83. if (stmt.type !== Syntax.ExpressionStatement) {
  84. break;
  85. }
  86. const expr = stmt.expression;
  87. if (expr.type !== Syntax.Literal || typeof expr.value !== "string") {
  88. break;
  89. }
  90. if (expr.raw !== null && expr.raw !== undefined) {
  91. if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") {
  92. return true;
  93. }
  94. } else {
  95. if (expr.value === "use strict") {
  96. return true;
  97. }
  98. }
  99. }
  100. }
  101. return false;
  102. }
  103. /**
  104. * Register scope
  105. * @param {ScopeManager} scopeManager - scope manager
  106. * @param {Scope} scope - scope
  107. * @returns {void}
  108. */
  109. function registerScope(scopeManager, scope) {
  110. scopeManager.scopes.push(scope);
  111. const scopes = scopeManager.__nodeToScope.get(scope.block);
  112. if (scopes) {
  113. scopes.push(scope);
  114. } else {
  115. scopeManager.__nodeToScope.set(scope.block, [scope]);
  116. }
  117. }
  118. /**
  119. * Should be statically
  120. * @param {Object} def - def
  121. * @returns {boolean} should be statically
  122. */
  123. function shouldBeStatically(def) {
  124. return (
  125. (def.type === Variable.ClassName) ||
  126. (def.type === Variable.Variable && def.parent.kind !== "var")
  127. );
  128. }
  129. /**
  130. * @class Scope
  131. */
  132. class Scope {
  133. constructor(scopeManager, type, upperScope, block, isMethodDefinition) {
  134. /**
  135. * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
  136. * @member {String} Scope#type
  137. */
  138. this.type = type;
  139. /**
  140. * The scoped {@link Variable}s of this scope, as <code>{ Variable.name
  141. * : Variable }</code>.
  142. * @member {Map} Scope#set
  143. */
  144. this.set = new Map();
  145. /**
  146. * The tainted variables of this scope, as <code>{ Variable.name :
  147. * boolean }</code>.
  148. * @member {Map} Scope#taints */
  149. this.taints = new Map();
  150. /**
  151. * Generally, through the lexical scoping of JS you can always know
  152. * which variable an identifier in the source code refers to. There are
  153. * a few exceptions to this rule. With 'global' and 'with' scopes you
  154. * can only decide at runtime which variable a reference refers to.
  155. * Moreover, if 'eval()' is used in a scope, it might introduce new
  156. * bindings in this or its parent scopes.
  157. * All those scopes are considered 'dynamic'.
  158. * @member {boolean} Scope#dynamic
  159. */
  160. this.dynamic = this.type === "global" || this.type === "with";
  161. /**
  162. * A reference to the scope-defining syntax node.
  163. * @member {espree.Node} Scope#block
  164. */
  165. this.block = block;
  166. /**
  167. * The {@link Reference|references} that are not resolved with this scope.
  168. * @member {Reference[]} Scope#through
  169. */
  170. this.through = [];
  171. /**
  172. * The scoped {@link Variable}s of this scope. In the case of a
  173. * 'function' scope this includes the automatic argument <em>arguments</em> as
  174. * its first element, as well as all further formal arguments.
  175. * @member {Variable[]} Scope#variables
  176. */
  177. this.variables = [];
  178. /**
  179. * Any variable {@link Reference|reference} found in this scope. This
  180. * includes occurrences of local variables as well as variables from
  181. * parent scopes (including the global scope). For local variables
  182. * this also includes defining occurrences (like in a 'var' statement).
  183. * In a 'function' scope this does not include the occurrences of the
  184. * formal parameter in the parameter list.
  185. * @member {Reference[]} Scope#references
  186. */
  187. this.references = [];
  188. /**
  189. * For 'global' and 'function' scopes, this is a self-reference. For
  190. * other scope types this is the <em>variableScope</em> value of the
  191. * parent scope.
  192. * @member {Scope} Scope#variableScope
  193. */
  194. this.variableScope =
  195. (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope;
  196. /**
  197. * Whether this scope is created by a FunctionExpression.
  198. * @member {boolean} Scope#functionExpressionScope
  199. */
  200. this.functionExpressionScope = false;
  201. /**
  202. * Whether this is a scope that contains an 'eval()' invocation.
  203. * @member {boolean} Scope#directCallToEvalScope
  204. */
  205. this.directCallToEvalScope = false;
  206. /**
  207. * @member {boolean} Scope#thisFound
  208. */
  209. this.thisFound = false;
  210. this.__left = [];
  211. /**
  212. * Reference to the parent {@link Scope|scope}.
  213. * @member {Scope} Scope#upper
  214. */
  215. this.upper = upperScope;
  216. /**
  217. * Whether 'use strict' is in effect in this scope.
  218. * @member {boolean} Scope#isStrict
  219. */
  220. this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());
  221. /**
  222. * List of nested {@link Scope}s.
  223. * @member {Scope[]} Scope#childScopes
  224. */
  225. this.childScopes = [];
  226. if (this.upper) {
  227. this.upper.childScopes.push(this);
  228. }
  229. this.__declaredVariables = scopeManager.__declaredVariables;
  230. registerScope(scopeManager, this);
  231. }
  232. __shouldStaticallyClose(scopeManager) {
  233. return (!this.dynamic || scopeManager.__isOptimistic());
  234. }
  235. __shouldStaticallyCloseForGlobal(ref) {
  236. // On global scope, let/const/class declarations should be resolved statically.
  237. const name = ref.identifier.name;
  238. if (!this.set.has(name)) {
  239. return false;
  240. }
  241. const variable = this.set.get(name);
  242. const defs = variable.defs;
  243. return defs.length > 0 && defs.every(shouldBeStatically);
  244. }
  245. __staticCloseRef(ref) {
  246. if (!this.__resolve(ref)) {
  247. this.__delegateToUpperScope(ref);
  248. }
  249. }
  250. __dynamicCloseRef(ref) {
  251. // notify all names are through to global
  252. let current = this;
  253. do {
  254. current.through.push(ref);
  255. current = current.upper;
  256. } while (current);
  257. }
  258. __globalCloseRef(ref) {
  259. // let/const/class declarations should be resolved statically.
  260. // others should be resolved dynamically.
  261. if (this.__shouldStaticallyCloseForGlobal(ref)) {
  262. this.__staticCloseRef(ref);
  263. } else {
  264. this.__dynamicCloseRef(ref);
  265. }
  266. }
  267. __close(scopeManager) {
  268. let closeRef;
  269. if (this.__shouldStaticallyClose(scopeManager)) {
  270. closeRef = this.__staticCloseRef;
  271. } else if (this.type !== "global") {
  272. closeRef = this.__dynamicCloseRef;
  273. } else {
  274. closeRef = this.__globalCloseRef;
  275. }
  276. // Try Resolving all references in this scope.
  277. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  278. const ref = this.__left[i];
  279. closeRef.call(this, ref);
  280. }
  281. this.__left = null;
  282. return this.upper;
  283. }
  284. // To override by function scopes.
  285. // References in default parameters isn't resolved to variables which are in their function body.
  286. __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars
  287. return true;
  288. }
  289. __resolve(ref) {
  290. const name = ref.identifier.name;
  291. if (!this.set.has(name)) {
  292. return false;
  293. }
  294. const variable = this.set.get(name);
  295. if (!this.__isValidResolution(ref, variable)) {
  296. return false;
  297. }
  298. variable.references.push(ref);
  299. variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
  300. if (ref.tainted) {
  301. variable.tainted = true;
  302. this.taints.set(variable.name, true);
  303. }
  304. ref.resolved = variable;
  305. return true;
  306. }
  307. __delegateToUpperScope(ref) {
  308. if (this.upper) {
  309. this.upper.__left.push(ref);
  310. }
  311. this.through.push(ref);
  312. }
  313. __addDeclaredVariablesOfNode(variable, node) {
  314. if (node === null || node === undefined) {
  315. return;
  316. }
  317. let variables = this.__declaredVariables.get(node);
  318. if (variables === null || variables === undefined) {
  319. variables = [];
  320. this.__declaredVariables.set(node, variables);
  321. }
  322. if (variables.indexOf(variable) === -1) {
  323. variables.push(variable);
  324. }
  325. }
  326. __defineGeneric(name, set, variables, node, def) {
  327. let variable;
  328. variable = set.get(name);
  329. if (!variable) {
  330. variable = new Variable(name, this);
  331. set.set(name, variable);
  332. variables.push(variable);
  333. }
  334. if (def) {
  335. variable.defs.push(def);
  336. this.__addDeclaredVariablesOfNode(variable, def.node);
  337. this.__addDeclaredVariablesOfNode(variable, def.parent);
  338. }
  339. if (node) {
  340. variable.identifiers.push(node);
  341. }
  342. }
  343. __define(node, def) {
  344. if (node && node.type === Syntax.Identifier) {
  345. this.__defineGeneric(
  346. node.name,
  347. this.set,
  348. this.variables,
  349. node,
  350. def
  351. );
  352. }
  353. }
  354. __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
  355. // because Array element may be null
  356. if (!node || node.type !== Syntax.Identifier) {
  357. return;
  358. }
  359. // Specially handle like `this`.
  360. if (node.name === "super") {
  361. return;
  362. }
  363. const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
  364. this.references.push(ref);
  365. this.__left.push(ref);
  366. }
  367. __detectEval() {
  368. let current = this;
  369. this.directCallToEvalScope = true;
  370. do {
  371. current.dynamic = true;
  372. current = current.upper;
  373. } while (current);
  374. }
  375. __detectThis() {
  376. this.thisFound = true;
  377. }
  378. __isClosed() {
  379. return this.__left === null;
  380. }
  381. /**
  382. * returns resolved {Reference}
  383. * @method Scope#resolve
  384. * @param {Espree.Identifier} ident - identifier to be resolved.
  385. * @returns {Reference} reference
  386. */
  387. resolve(ident) {
  388. let ref, i, iz;
  389. assert(this.__isClosed(), "Scope should be closed.");
  390. assert(ident.type === Syntax.Identifier, "Target should be identifier.");
  391. for (i = 0, iz = this.references.length; i < iz; ++i) {
  392. ref = this.references[i];
  393. if (ref.identifier === ident) {
  394. return ref;
  395. }
  396. }
  397. return null;
  398. }
  399. /**
  400. * returns this scope is static
  401. * @method Scope#isStatic
  402. * @returns {boolean} static
  403. */
  404. isStatic() {
  405. return !this.dynamic;
  406. }
  407. /**
  408. * returns this scope has materialized arguments
  409. * @method Scope#isArgumentsMaterialized
  410. * @returns {boolean} arguemnts materialized
  411. */
  412. isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this
  413. return true;
  414. }
  415. /**
  416. * returns this scope has materialized `this` reference
  417. * @method Scope#isThisMaterialized
  418. * @returns {boolean} this materialized
  419. */
  420. isThisMaterialized() { // eslint-disable-line class-methods-use-this
  421. return true;
  422. }
  423. isUsedName(name) {
  424. if (this.set.has(name)) {
  425. return true;
  426. }
  427. for (let i = 0, iz = this.through.length; i < iz; ++i) {
  428. if (this.through[i].identifier.name === name) {
  429. return true;
  430. }
  431. }
  432. return false;
  433. }
  434. }
  435. class GlobalScope extends Scope {
  436. constructor(scopeManager, block) {
  437. super(scopeManager, "global", null, block, false);
  438. this.implicit = {
  439. set: new Map(),
  440. variables: [],
  441. /**
  442. * List of {@link Reference}s that are left to be resolved (i.e. which
  443. * need to be linked to the variable they refer to).
  444. * @member {Reference[]} Scope#implicit#left
  445. */
  446. left: []
  447. };
  448. }
  449. __close(scopeManager) {
  450. const implicit = [];
  451. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  452. const ref = this.__left[i];
  453. if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
  454. implicit.push(ref.__maybeImplicitGlobal);
  455. }
  456. }
  457. // create an implicit global variable from assignment expression
  458. for (let i = 0, iz = implicit.length; i < iz; ++i) {
  459. const info = implicit[i];
  460. this.__defineImplicit(info.pattern,
  461. new Definition(
  462. Variable.ImplicitGlobalVariable,
  463. info.pattern,
  464. info.node,
  465. null,
  466. null,
  467. null
  468. ));
  469. }
  470. this.implicit.left = this.__left;
  471. return super.__close(scopeManager);
  472. }
  473. __defineImplicit(node, def) {
  474. if (node && node.type === Syntax.Identifier) {
  475. this.__defineGeneric(
  476. node.name,
  477. this.implicit.set,
  478. this.implicit.variables,
  479. node,
  480. def
  481. );
  482. }
  483. }
  484. }
  485. class ModuleScope extends Scope {
  486. constructor(scopeManager, upperScope, block) {
  487. super(scopeManager, "module", upperScope, block, false);
  488. }
  489. }
  490. class FunctionExpressionNameScope extends Scope {
  491. constructor(scopeManager, upperScope, block) {
  492. super(scopeManager, "function-expression-name", upperScope, block, false);
  493. this.__define(block.id,
  494. new Definition(
  495. Variable.FunctionName,
  496. block.id,
  497. block,
  498. null,
  499. null,
  500. null
  501. ));
  502. this.functionExpressionScope = true;
  503. }
  504. }
  505. class CatchScope extends Scope {
  506. constructor(scopeManager, upperScope, block) {
  507. super(scopeManager, "catch", upperScope, block, false);
  508. }
  509. }
  510. class WithScope extends Scope {
  511. constructor(scopeManager, upperScope, block) {
  512. super(scopeManager, "with", upperScope, block, false);
  513. }
  514. __close(scopeManager) {
  515. if (this.__shouldStaticallyClose(scopeManager)) {
  516. return super.__close(scopeManager);
  517. }
  518. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  519. const ref = this.__left[i];
  520. ref.tainted = true;
  521. this.__delegateToUpperScope(ref);
  522. }
  523. this.__left = null;
  524. return this.upper;
  525. }
  526. }
  527. class BlockScope extends Scope {
  528. constructor(scopeManager, upperScope, block) {
  529. super(scopeManager, "block", upperScope, block, false);
  530. }
  531. }
  532. class SwitchScope extends Scope {
  533. constructor(scopeManager, upperScope, block) {
  534. super(scopeManager, "switch", upperScope, block, false);
  535. }
  536. }
  537. class FunctionScope extends Scope {
  538. constructor(scopeManager, upperScope, block, isMethodDefinition) {
  539. super(scopeManager, "function", upperScope, block, isMethodDefinition);
  540. // section 9.2.13, FunctionDeclarationInstantiation.
  541. // NOTE Arrow functions never have an arguments objects.
  542. if (this.block.type !== Syntax.ArrowFunctionExpression) {
  543. this.__defineArguments();
  544. }
  545. }
  546. isArgumentsMaterialized() {
  547. // TODO(Constellation)
  548. // We can more aggressive on this condition like this.
  549. //
  550. // function t() {
  551. // // arguments of t is always hidden.
  552. // function arguments() {
  553. // }
  554. // }
  555. if (this.block.type === Syntax.ArrowFunctionExpression) {
  556. return false;
  557. }
  558. if (!this.isStatic()) {
  559. return true;
  560. }
  561. const variable = this.set.get("arguments");
  562. assert(variable, "Always have arguments variable.");
  563. return variable.tainted || variable.references.length !== 0;
  564. }
  565. isThisMaterialized() {
  566. if (!this.isStatic()) {
  567. return true;
  568. }
  569. return this.thisFound;
  570. }
  571. __defineArguments() {
  572. this.__defineGeneric(
  573. "arguments",
  574. this.set,
  575. this.variables,
  576. null,
  577. null
  578. );
  579. this.taints.set("arguments", true);
  580. }
  581. // References in default parameters isn't resolved to variables which are in their function body.
  582. // const x = 1
  583. // function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
  584. // const x = 2
  585. // console.log(a)
  586. // }
  587. __isValidResolution(ref, variable) {
  588. // If `options.nodejsScope` is true, `this.block` becomes a Program node.
  589. if (this.block.type === "Program") {
  590. return true;
  591. }
  592. const bodyStart = this.block.body.range[0];
  593. // It's invalid resolution in the following case:
  594. return !(
  595. variable.scope === this &&
  596. ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
  597. variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
  598. );
  599. }
  600. }
  601. class ForScope extends Scope {
  602. constructor(scopeManager, upperScope, block) {
  603. super(scopeManager, "for", upperScope, block, false);
  604. }
  605. }
  606. class ClassScope extends Scope {
  607. constructor(scopeManager, upperScope, block) {
  608. super(scopeManager, "class", upperScope, block, false);
  609. }
  610. }
  611. module.exports = {
  612. Scope,
  613. GlobalScope,
  614. ModuleScope,
  615. FunctionExpressionNameScope,
  616. CatchScope,
  617. WithScope,
  618. BlockScope,
  619. SwitchScope,
  620. FunctionScope,
  621. ForScope,
  622. ClassScope
  623. };
  624. /* vim: set sw=4 ts=4 et tw=80 : */