scope.js 22 KB

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