Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scope.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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. // ArrowFunctionExpression's scope is always strict scope.
  44. if (block.type === Syntax.ArrowFunctionExpression) {
  45. return true;
  46. }
  47. if (isMethodDefinition) {
  48. return true;
  49. }
  50. if (scope.type === "class" || scope.type === "module") {
  51. return true;
  52. }
  53. if (scope.type === "block" || scope.type === "switch") {
  54. return false;
  55. }
  56. if (scope.type === "function") {
  57. if (block.type === Syntax.Program) {
  58. body = block;
  59. } else {
  60. body = block.body;
  61. }
  62. if (!body) {
  63. return false;
  64. }
  65. } else if (scope.type === "global") {
  66. body = block;
  67. } else {
  68. return false;
  69. }
  70. // Search 'use strict' directive.
  71. if (useDirective) {
  72. for (let i = 0, iz = body.body.length; i < iz; ++i) {
  73. const stmt = body.body[i];
  74. if (stmt.type !== Syntax.DirectiveStatement) {
  75. break;
  76. }
  77. if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") {
  78. return true;
  79. }
  80. }
  81. } else {
  82. for (let i = 0, iz = body.body.length; i < iz; ++i) {
  83. const stmt = body.body[i];
  84. if (stmt.type !== Syntax.ExpressionStatement) {
  85. break;
  86. }
  87. const expr = stmt.expression;
  88. if (expr.type !== Syntax.Literal || typeof expr.value !== "string") {
  89. break;
  90. }
  91. if (expr.raw !== null && expr.raw !== undefined) {
  92. if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") {
  93. return true;
  94. }
  95. } else {
  96. if (expr.value === "use strict") {
  97. return true;
  98. }
  99. }
  100. }
  101. }
  102. return false;
  103. }
  104. /**
  105. * Register scope
  106. * @param {ScopeManager} scopeManager - scope manager
  107. * @param {Scope} scope - scope
  108. * @returns {void}
  109. */
  110. function registerScope(scopeManager, scope) {
  111. scopeManager.scopes.push(scope);
  112. const scopes = scopeManager.__nodeToScope.get(scope.block);
  113. if (scopes) {
  114. scopes.push(scope);
  115. } else {
  116. scopeManager.__nodeToScope.set(scope.block, [scope]);
  117. }
  118. }
  119. /**
  120. * Should be statically
  121. * @param {Object} def - def
  122. * @returns {boolean} should be statically
  123. */
  124. function shouldBeStatically(def) {
  125. return (
  126. (def.type === Variable.ClassName) ||
  127. (def.type === Variable.Variable && def.parent.kind !== "var")
  128. );
  129. }
  130. /**
  131. * @class Scope
  132. */
  133. class Scope {
  134. constructor(scopeManager, type, upperScope, block, isMethodDefinition) {
  135. /**
  136. * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
  137. * @member {String} Scope#type
  138. */
  139. this.type = type;
  140. /**
  141. * The scoped {@link Variable}s of this scope, as <code>{ Variable.name
  142. * : Variable }</code>.
  143. * @member {Map} Scope#set
  144. */
  145. this.set = new Map();
  146. /**
  147. * The tainted variables of this scope, as <code>{ Variable.name :
  148. * boolean }</code>.
  149. * @member {Map} Scope#taints */
  150. this.taints = new Map();
  151. /**
  152. * Generally, through the lexical scoping of JS you can always know
  153. * which variable an identifier in the source code refers to. There are
  154. * a few exceptions to this rule. With 'global' and 'with' scopes you
  155. * can only decide at runtime which variable a reference refers to.
  156. * Moreover, if 'eval()' is used in a scope, it might introduce new
  157. * bindings in this or its parent scopes.
  158. * All those scopes are considered 'dynamic'.
  159. * @member {boolean} Scope#dynamic
  160. */
  161. this.dynamic = this.type === "global" || this.type === "with";
  162. /**
  163. * A reference to the scope-defining syntax node.
  164. * @member {espree.Node} Scope#block
  165. */
  166. this.block = block;
  167. /**
  168. * The {@link Reference|references} that are not resolved with this scope.
  169. * @member {Reference[]} Scope#through
  170. */
  171. this.through = [];
  172. /**
  173. * The scoped {@link Variable}s of this scope. In the case of a
  174. * 'function' scope this includes the automatic argument <em>arguments</em> as
  175. * its first element, as well as all further formal arguments.
  176. * @member {Variable[]} Scope#variables
  177. */
  178. this.variables = [];
  179. /**
  180. * Any variable {@link Reference|reference} found in this scope. This
  181. * includes occurrences of local variables as well as variables from
  182. * parent scopes (including the global scope). For local variables
  183. * this also includes defining occurrences (like in a 'var' statement).
  184. * In a 'function' scope this does not include the occurrences of the
  185. * formal parameter in the parameter list.
  186. * @member {Reference[]} Scope#references
  187. */
  188. this.references = [];
  189. /**
  190. * For 'global' and 'function' scopes, this is a self-reference. For
  191. * other scope types this is the <em>variableScope</em> value of the
  192. * parent scope.
  193. * @member {Scope} Scope#variableScope
  194. */
  195. this.variableScope =
  196. (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope;
  197. /**
  198. * Whether this scope is created by a FunctionExpression.
  199. * @member {boolean} Scope#functionExpressionScope
  200. */
  201. this.functionExpressionScope = false;
  202. /**
  203. * Whether this is a scope that contains an 'eval()' invocation.
  204. * @member {boolean} Scope#directCallToEvalScope
  205. */
  206. this.directCallToEvalScope = false;
  207. /**
  208. * @member {boolean} Scope#thisFound
  209. */
  210. this.thisFound = false;
  211. this.__left = [];
  212. /**
  213. * Reference to the parent {@link Scope|scope}.
  214. * @member {Scope} Scope#upper
  215. */
  216. this.upper = upperScope;
  217. /**
  218. * Whether 'use strict' is in effect in this scope.
  219. * @member {boolean} Scope#isStrict
  220. */
  221. this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());
  222. /**
  223. * List of nested {@link Scope}s.
  224. * @member {Scope[]} Scope#childScopes
  225. */
  226. this.childScopes = [];
  227. if (this.upper) {
  228. this.upper.childScopes.push(this);
  229. }
  230. this.__declaredVariables = scopeManager.__declaredVariables;
  231. registerScope(scopeManager, this);
  232. }
  233. __shouldStaticallyClose(scopeManager) {
  234. return (!this.dynamic || scopeManager.__isOptimistic());
  235. }
  236. __shouldStaticallyCloseForGlobal(ref) {
  237. // On global scope, let/const/class declarations should be resolved statically.
  238. const name = ref.identifier.name;
  239. if (!this.set.has(name)) {
  240. return false;
  241. }
  242. const variable = this.set.get(name);
  243. const defs = variable.defs;
  244. return defs.length > 0 && defs.every(shouldBeStatically);
  245. }
  246. __staticCloseRef(ref) {
  247. if (!this.__resolve(ref)) {
  248. this.__delegateToUpperScope(ref);
  249. }
  250. }
  251. __dynamicCloseRef(ref) {
  252. // notify all names are through to global
  253. let current = this;
  254. do {
  255. current.through.push(ref);
  256. current = current.upper;
  257. } while (current);
  258. }
  259. __globalCloseRef(ref) {
  260. // let/const/class declarations should be resolved statically.
  261. // others should be resolved dynamically.
  262. if (this.__shouldStaticallyCloseForGlobal(ref)) {
  263. this.__staticCloseRef(ref);
  264. } else {
  265. this.__dynamicCloseRef(ref);
  266. }
  267. }
  268. __close(scopeManager) {
  269. let closeRef;
  270. if (this.__shouldStaticallyClose(scopeManager)) {
  271. closeRef = this.__staticCloseRef;
  272. } else if (this.type !== "global") {
  273. closeRef = this.__dynamicCloseRef;
  274. } else {
  275. closeRef = this.__globalCloseRef;
  276. }
  277. // Try Resolving all references in this scope.
  278. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  279. const ref = this.__left[i];
  280. closeRef.call(this, ref);
  281. }
  282. this.__left = null;
  283. return this.upper;
  284. }
  285. // To override by function scopes.
  286. // References in default parameters isn't resolved to variables which are in their function body.
  287. __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars
  288. return true;
  289. }
  290. __resolve(ref) {
  291. const name = ref.identifier.name;
  292. if (!this.set.has(name)) {
  293. return false;
  294. }
  295. const variable = this.set.get(name);
  296. if (!this.__isValidResolution(ref, variable)) {
  297. return false;
  298. }
  299. variable.references.push(ref);
  300. variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
  301. if (ref.tainted) {
  302. variable.tainted = true;
  303. this.taints.set(variable.name, true);
  304. }
  305. ref.resolved = variable;
  306. return true;
  307. }
  308. __delegateToUpperScope(ref) {
  309. if (this.upper) {
  310. this.upper.__left.push(ref);
  311. }
  312. this.through.push(ref);
  313. }
  314. __addDeclaredVariablesOfNode(variable, node) {
  315. if (node === null || node === undefined) {
  316. return;
  317. }
  318. let variables = this.__declaredVariables.get(node);
  319. if (variables === null || variables === undefined) {
  320. variables = [];
  321. this.__declaredVariables.set(node, variables);
  322. }
  323. if (variables.indexOf(variable) === -1) {
  324. variables.push(variable);
  325. }
  326. }
  327. __defineGeneric(name, set, variables, node, def) {
  328. let variable;
  329. variable = set.get(name);
  330. if (!variable) {
  331. variable = new Variable(name, this);
  332. set.set(name, variable);
  333. variables.push(variable);
  334. }
  335. if (def) {
  336. variable.defs.push(def);
  337. this.__addDeclaredVariablesOfNode(variable, def.node);
  338. this.__addDeclaredVariablesOfNode(variable, def.parent);
  339. }
  340. if (node) {
  341. variable.identifiers.push(node);
  342. }
  343. }
  344. __define(node, def) {
  345. if (node && node.type === Syntax.Identifier) {
  346. this.__defineGeneric(
  347. node.name,
  348. this.set,
  349. this.variables,
  350. node,
  351. def);
  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. class ModuleScope extends Scope {
  485. constructor(scopeManager, upperScope, block) {
  486. super(scopeManager, "module", upperScope, block, false);
  487. }
  488. }
  489. class FunctionExpressionNameScope extends Scope {
  490. constructor(scopeManager, upperScope, block) {
  491. super(scopeManager, "function-expression-name", upperScope, block, false);
  492. this.__define(block.id,
  493. new Definition(
  494. Variable.FunctionName,
  495. block.id,
  496. block,
  497. null,
  498. null,
  499. null
  500. ));
  501. this.functionExpressionScope = true;
  502. }
  503. }
  504. class CatchScope extends Scope {
  505. constructor(scopeManager, upperScope, block) {
  506. super(scopeManager, "catch", upperScope, block, false);
  507. }
  508. }
  509. class WithScope extends Scope {
  510. constructor(scopeManager, upperScope, block) {
  511. super(scopeManager, "with", upperScope, block, false);
  512. }
  513. __close(scopeManager) {
  514. if (this.__shouldStaticallyClose(scopeManager)) {
  515. return super.__close(scopeManager);
  516. }
  517. for (let i = 0, iz = this.__left.length; i < iz; ++i) {
  518. const ref = this.__left[i];
  519. ref.tainted = true;
  520. this.__delegateToUpperScope(ref);
  521. }
  522. this.__left = null;
  523. return this.upper;
  524. }
  525. }
  526. class BlockScope extends Scope {
  527. constructor(scopeManager, upperScope, block) {
  528. super(scopeManager, "block", upperScope, block, false);
  529. }
  530. }
  531. class SwitchScope extends Scope {
  532. constructor(scopeManager, upperScope, block) {
  533. super(scopeManager, "switch", upperScope, block, false);
  534. }
  535. }
  536. class FunctionScope extends Scope {
  537. constructor(scopeManager, upperScope, block, isMethodDefinition) {
  538. super(scopeManager, "function", upperScope, block, isMethodDefinition);
  539. // section 9.2.13, FunctionDeclarationInstantiation.
  540. // NOTE Arrow functions never have an arguments objects.
  541. if (this.block.type !== Syntax.ArrowFunctionExpression) {
  542. this.__defineArguments();
  543. }
  544. }
  545. isArgumentsMaterialized() {
  546. // TODO(Constellation)
  547. // We can more aggressive on this condition like this.
  548. //
  549. // function t() {
  550. // // arguments of t is always hidden.
  551. // function arguments() {
  552. // }
  553. // }
  554. if (this.block.type === Syntax.ArrowFunctionExpression) {
  555. return false;
  556. }
  557. if (!this.isStatic()) {
  558. return true;
  559. }
  560. const variable = this.set.get("arguments");
  561. assert(variable, "Always have arguments variable.");
  562. return variable.tainted || variable.references.length !== 0;
  563. }
  564. isThisMaterialized() {
  565. if (!this.isStatic()) {
  566. return true;
  567. }
  568. return this.thisFound;
  569. }
  570. __defineArguments() {
  571. this.__defineGeneric(
  572. "arguments",
  573. this.set,
  574. this.variables,
  575. null,
  576. null);
  577. this.taints.set("arguments", true);
  578. }
  579. // References in default parameters isn't resolved to variables which are in their function body.
  580. // const x = 1
  581. // function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
  582. // const x = 2
  583. // console.log(a)
  584. // }
  585. __isValidResolution(ref, variable) {
  586. // If `options.nodejsScope` is true, `this.block` becomes a Program node.
  587. if (this.block.type === "Program") {
  588. return true;
  589. }
  590. const bodyStart = this.block.body.range[0];
  591. // It's invalid resolution in the following case:
  592. return !(
  593. variable.scope === this &&
  594. ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
  595. variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
  596. );
  597. }
  598. }
  599. class ForScope extends Scope {
  600. constructor(scopeManager, upperScope, block) {
  601. super(scopeManager, "for", upperScope, block, false);
  602. }
  603. }
  604. class ClassScope extends Scope {
  605. constructor(scopeManager, upperScope, block) {
  606. super(scopeManager, "class", upperScope, block, false);
  607. }
  608. }
  609. module.exports = {
  610. Scope,
  611. GlobalScope,
  612. ModuleScope,
  613. FunctionExpressionNameScope,
  614. CatchScope,
  615. WithScope,
  616. BlockScope,
  617. SwitchScope,
  618. FunctionScope,
  619. ForScope,
  620. ClassScope
  621. };
  622. /* vim: set sw=4 ts=4 et tw=80 : */