scope.js 19 KB

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