Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

scope.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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 definiton
  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. __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
  354. // because Array element may be null
  355. if (!node || node.type !== Syntax.Identifier) {
  356. return;
  357. }
  358. // Specially handle like `this`.
  359. if (node.name === "super") {
  360. return;
  361. }
  362. const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
  363. this.references.push(ref);
  364. this.__left.push(ref);
  365. }
  366. __detectEval() {
  367. let current = this;
  368. this.directCallToEvalScope = true;
  369. do {
  370. current.dynamic = true;
  371. current = current.upper;
  372. } while (current);
  373. }
  374. __detectThis() {
  375. this.thisFound = true;
  376. }
  377. __isClosed() {
  378. return this.__left === null;
  379. }
  380. /**
  381. * returns resolved {Reference}
  382. * @method Scope#resolve
  383. * @param {Espree.Identifier} ident - identifier to be resolved.
  384. * @returns {Reference} reference
  385. */
  386. resolve(ident) {
  387. let ref, i, iz;
  388. assert(this.__isClosed(), "Scope should be closed.");
  389. assert(ident.type === Syntax.Identifier, "Target should be identifier.");
  390. for (i = 0, iz = this.references.length; i < iz; ++i) {
  391. ref = this.references[i];
  392. if (ref.identifier === ident) {
  393. return ref;
  394. }
  395. }
  396. return null;
  397. }
  398. /**
  399. * returns this scope is static
  400. * @method Scope#isStatic
  401. * @returns {boolean} static
  402. */
  403. isStatic() {
  404. return !this.dynamic;
  405. }
  406. /**
  407. * returns this scope has materialized arguments
  408. * @method Scope#isArgumentsMaterialized
  409. * @returns {boolean} arguemnts materialized
  410. */
  411. isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this
  412. return true;
  413. }
  414. /**
  415. * returns this scope has materialized `this` reference
  416. * @method Scope#isThisMaterialized
  417. * @returns {boolean} this materialized
  418. */
  419. isThisMaterialized() { // eslint-disable-line class-methods-use-this
  420. return true;
  421. }
  422. isUsedName(name) {
  423. if (this.set.has(name)) {
  424. return true;
  425. }
  426. for (let i = 0, iz = this.through.length; i < iz; ++i) {
  427. if (this.through[i].identifier.name === name) {
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. }
  434. class GlobalScope extends Scope {
  435. constructor(scopeManager, block) {
  436. super(scopeManager, "global", null, block, false);
  437. this.implicit = {
  438. set: new Map(),
  439. variables: [],
  440. /**
  441. * List of {@link Reference}s that are left to be resolved (i.e. which
  442. * need to be linked to the variable they refer to).
  443. * @member {Reference[]} Scope#implicit#left
  444. */
  445. left: []
  446. };
  447. }
  448. __close(scopeManager) {
  449. const implicit = [];
  450. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  451. const ref = this.__left[i];
  452. if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
  453. implicit.push(ref.__maybeImplicitGlobal);
  454. }
  455. }
  456. // create an implicit global variable from assignment expression
  457. for (let i = 0, iz = implicit.length; i < iz; ++i) {
  458. const info = implicit[i];
  459. this.__defineImplicit(info.pattern,
  460. new Definition(
  461. Variable.ImplicitGlobalVariable,
  462. info.pattern,
  463. info.node,
  464. null,
  465. null,
  466. null
  467. ));
  468. }
  469. this.implicit.left = this.__left;
  470. return super.__close(scopeManager);
  471. }
  472. __defineImplicit(node, def) {
  473. if (node && node.type === Syntax.Identifier) {
  474. this.__defineGeneric(
  475. node.name,
  476. this.implicit.set,
  477. this.implicit.variables,
  478. node,
  479. def);
  480. }
  481. }
  482. }
  483. class ModuleScope extends Scope {
  484. constructor(scopeManager, upperScope, block) {
  485. super(scopeManager, "module", upperScope, block, false);
  486. }
  487. }
  488. class FunctionExpressionNameScope extends Scope {
  489. constructor(scopeManager, upperScope, block) {
  490. super(scopeManager, "function-expression-name", upperScope, block, false);
  491. this.__define(block.id,
  492. new Definition(
  493. Variable.FunctionName,
  494. block.id,
  495. block,
  496. null,
  497. null,
  498. null
  499. ));
  500. this.functionExpressionScope = true;
  501. }
  502. }
  503. class CatchScope extends Scope {
  504. constructor(scopeManager, upperScope, block) {
  505. super(scopeManager, "catch", upperScope, block, false);
  506. }
  507. }
  508. class WithScope extends Scope {
  509. constructor(scopeManager, upperScope, block) {
  510. super(scopeManager, "with", upperScope, block, false);
  511. }
  512. __close(scopeManager) {
  513. if (this.__shouldStaticallyClose(scopeManager)) {
  514. return super.__close(scopeManager);
  515. }
  516. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  517. const ref = this.__left[i];
  518. ref.tainted = true;
  519. this.__delegateToUpperScope(ref);
  520. }
  521. this.__left = null;
  522. return this.upper;
  523. }
  524. }
  525. class BlockScope extends Scope {
  526. constructor(scopeManager, upperScope, block) {
  527. super(scopeManager, "block", upperScope, block, false);
  528. }
  529. }
  530. class SwitchScope extends Scope {
  531. constructor(scopeManager, upperScope, block) {
  532. super(scopeManager, "switch", upperScope, block, false);
  533. }
  534. }
  535. class FunctionScope extends Scope {
  536. constructor(scopeManager, upperScope, block, isMethodDefinition) {
  537. super(scopeManager, "function", upperScope, block, isMethodDefinition);
  538. // section 9.2.13, FunctionDeclarationInstantiation.
  539. // NOTE Arrow functions never have an arguments objects.
  540. if (this.block.type !== Syntax.ArrowFunctionExpression) {
  541. this.__defineArguments();
  542. }
  543. }
  544. isArgumentsMaterialized() {
  545. // TODO(Constellation)
  546. // We can more aggressive on this condition like this.
  547. //
  548. // function t() {
  549. // // arguments of t is always hidden.
  550. // function arguments() {
  551. // }
  552. // }
  553. if (this.block.type === Syntax.ArrowFunctionExpression) {
  554. return false;
  555. }
  556. if (!this.isStatic()) {
  557. return true;
  558. }
  559. const variable = this.set.get("arguments");
  560. assert(variable, "Always have arguments variable.");
  561. return variable.tainted || variable.references.length !== 0;
  562. }
  563. isThisMaterialized() {
  564. if (!this.isStatic()) {
  565. return true;
  566. }
  567. return this.thisFound;
  568. }
  569. __defineArguments() {
  570. this.__defineGeneric(
  571. "arguments",
  572. this.set,
  573. this.variables,
  574. null,
  575. null);
  576. this.taints.set("arguments", true);
  577. }
  578. // References in default parameters isn't resolved to variables which are in their function body.
  579. // const x = 1
  580. // function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
  581. // const x = 2
  582. // console.log(a)
  583. // }
  584. __isValidResolution(ref, variable) {
  585. // If `options.nodejsScope` is true, `this.block` becomes a Program node.
  586. if (this.block.type === "Program") {
  587. return true;
  588. }
  589. const bodyStart = this.block.body.range[0];
  590. // It's invalid resolution in the following case:
  591. return !(
  592. variable.scope === this &&
  593. ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
  594. variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
  595. );
  596. }
  597. }
  598. class ForScope extends Scope {
  599. constructor(scopeManager, upperScope, block) {
  600. super(scopeManager, "for", upperScope, block, false);
  601. }
  602. }
  603. class ClassScope extends Scope {
  604. constructor(scopeManager, upperScope, block) {
  605. super(scopeManager, "class", upperScope, block, false);
  606. }
  607. }
  608. module.exports = {
  609. Scope,
  610. GlobalScope,
  611. ModuleScope,
  612. FunctionExpressionNameScope,
  613. CatchScope,
  614. WithScope,
  615. BlockScope,
  616. SwitchScope,
  617. FunctionScope,
  618. ForScope,
  619. ClassScope
  620. };
  621. /* vim: set sw=4 ts=4 et tw=80 : */