|
14 | 14 |
|
15 | 15 | import javascript |
16 | 16 |
|
17 | | -from BindingPattern p, string n, VarDecl v, VarDecl w |
| 17 | +class RootDestructuringPattern extends BindingPattern { |
| 18 | + RootDestructuringPattern() { |
| 19 | + this instanceof DestructuringPattern and |
| 20 | + not this = any(PropertyPattern p).getValuePattern() and |
| 21 | + not this = any(ArrayPattern p).getAnElement() |
| 22 | + } |
| 23 | + |
| 24 | + /** Holds if this pattern has multiple bindings for `name`. */ |
| 25 | + predicate hasConflictingBindings(string name) { |
| 26 | + exists(VarRef v, VarRef w | |
| 27 | + v = getABindingVarRef() and |
| 28 | + w = getABindingVarRef() and |
| 29 | + name = v.getName() and |
| 30 | + name = w.getName() and |
| 31 | + v != w |
| 32 | + ) |
| 33 | + } |
| 34 | + |
| 35 | + /** Gets the first occurrence of the conflicting binding `name`. */ |
| 36 | + VarDecl getFirstClobberedVarDecl(string name) { |
| 37 | + hasConflictingBindings(name) and |
| 38 | + result = |
| 39 | + min(VarDecl decl | |
| 40 | + decl = getABindingVarRef() and decl.getName() = name |
| 41 | + | |
| 42 | + decl order by decl.getLocation().getStartLine(), decl.getLocation().getStartColumn() |
| 43 | + ) |
| 44 | + } |
| 45 | + |
| 46 | + /** Holds if variables in this pattern may resemble type annotations. */ |
| 47 | + predicate resemblesTypeAnnotation() { |
| 48 | + hasConflictingBindings(_) and // Restrict size of predicate. |
| 49 | + this instanceof Parameter and |
| 50 | + this instanceof ObjectPattern and |
| 51 | + not exists(getTypeAnnotation()) and |
| 52 | + getFile().getFileType().isTypeScript() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +from RootDestructuringPattern p, string n, VarDecl v, VarDecl w, string message |
18 | 57 | where |
19 | | - v = p.getABindingVarRef() and |
| 58 | + v = p.getFirstClobberedVarDecl(n) and |
20 | 59 | w = p.getABindingVarRef() and |
21 | | - v.getName() = n and |
22 | 60 | w.getName() = n and |
23 | 61 | v != w and |
24 | | - v.getLocation().startsBefore(w.getLocation()) |
25 | | -select w, "Repeated binding of pattern variable '" + n + "' previously bound $@.", v, "here" |
| 62 | + if p.resemblesTypeAnnotation() |
| 63 | + then |
| 64 | + message = |
| 65 | + "The pattern variable '" + n + |
| 66 | + "' appears to be a type, but is a variable previously bound $@." |
| 67 | + else message = "Repeated binding of pattern variable '" + n + "' previously bound $@." |
| 68 | +select w, message, v, "here" |
0 commit comments