UNPKG

1.93 kBJavaScriptView Raw
1import { blank } from '../utils/object';
2
3const extractors = {
4 Identifier ( names, param ) {
5 names.push( param.name );
6 },
7
8 ObjectPattern ( names, param ) {
9 param.properties.forEach( prop => {
10 extractors[ prop.key.type ]( names, prop.key );
11 });
12 },
13
14 ArrayPattern ( names, param ) {
15 param.elements.forEach( element => {
16 if ( element ) extractors[ element.type ]( names, element );
17 });
18 },
19
20 RestElement ( names, param ) {
21 extractors[ param.argument.type ]( names, param.argument );
22 },
23
24 AssignmentPattern ( names, param ) {
25 return extractors[ param.left.type ]( names, param.left );
26 }
27};
28
29function extractNames ( param ) {
30 let names = [];
31
32 extractors[ param.type ]( names, param );
33 return names;
34}
35
36export default class Scope {
37 constructor ( options ) {
38 options = options || {};
39
40 this.parent = options.parent;
41 this.depth = this.parent ? this.parent.depth + 1 : 0;
42 this.declarations = blank();
43 this.isBlockScope = !!options.block;
44
45 this.varDeclarations = [];
46
47 if ( options.params ) {
48 options.params.forEach( param => {
49 extractNames( param ).forEach( name => {
50 this.declarations[ name ] = true;
51 });
52 });
53 }
54 }
55
56 addDeclaration ( declaration, isBlockDeclaration, isVar ) {
57 if ( !isBlockDeclaration && this.isBlockScope ) {
58 // it's a `var` or function node, and this
59 // is a block scope, so we need to go up
60 this.parent.addDeclaration( declaration, isBlockDeclaration, isVar );
61 } else {
62 extractNames( declaration.id ).forEach( name => {
63 this.declarations[ name ] = true;
64 if ( isVar ) this.varDeclarations.push( name );
65 });
66 }
67 }
68
69 contains ( name ) {
70 return this.declarations[ name ] ||
71 ( this.parent ? this.parent.contains( name ) : false );
72 }
73
74 findDefiningScope ( name ) {
75 if ( this.declarations[ name ] ) {
76 return this;
77 }
78
79 if ( this.parent ) {
80 return this.parent.findDefiningScope( name );
81 }
82
83 return null;
84 }
85}