JS: add utility SyntacticConstants::isNullOrUndefined

This commit is contained in:
Esben Sparre Andreasen
2018-10-12 14:36:57 +02:00
parent 7c7cd7c213
commit ec1722c4db
3 changed files with 22 additions and 21 deletions

View File

@@ -25,25 +25,6 @@ predicate deadStoreOfLocal(VarDef vd, PurelyLocalVariable v) {
not exists (SsaExplicitDefinition ssa | ssa.defines(vd, v))
}
/**
* Holds if `e` is an expression evaluating to `null` or `undefined`.
*
* This includes not only direct references to `null` and `undefined`, but
* also `void` expressions and assignments of the form `x = rhs`, where `rhs`
* is itself an expression evaluating to `null` or `undefined`.
*/
predicate isNullOrUndef(Expr e) {
exists (Expr inner |
inner = e.stripParens() |
// `null` or `undefined`
inner instanceof NullLiteral or
inner.(VarAccess).getName() = "undefined" or
inner instanceof VoidExpr or
// recursive case to catch multi-assignments of the form `x = y = null`
isNullOrUndef(inner.(AssignExpr).getRhs())
)
}
/**
* Holds if `e` is an expression that may be used as a default initial value,
* such as `0` or `-1`, or an empty object or array literal.
@@ -77,7 +58,7 @@ where deadStoreOfLocal(dead, v) and
not fd = outer.getBody().(BlockStmt).getAStmt()
) and
// don't flag overwrites with `null` or `undefined`
not isNullOrUndef(dead.getSource()) and
not SyntacticConstants::isNullOrUndefined(dead.getSource()) and
// don't flag default inits that are later overwritten
not (isDefaultInit(dead.getSource()) and dead.isOverwritten(v)) and
// don't flag assignments in externs

View File

@@ -132,6 +132,27 @@ module SyntacticConstants {
}
/**
* Holds if `c` evaluates to `undefined`.
*/
predicate isUndefined(SyntacticConstant c) {
c.getUnderlyingValue() instanceof UndefinedConstant
}
/**
* Holds if `c` evaluates to `null`.
*/
predicate isNull(SyntacticConstant c) {
c.getUnderlyingValue() instanceof NullConstant
}
/**
* Holds if `c` evaluates to `null` or `undefined`.
*/
predicate isNullOrUndefined(SyntacticConstant c) {
isUndefined(c) or isNull(c)
}
}
/**

View File

@@ -58,7 +58,6 @@
| tst.js:47:5:47:5 | 1 |
| tst.js:48:1:48:7 | x.p = 1 |
| tst.js:48:7:48:7 | 1 |
| tst.js:49:1:49:6 | x += 1 |
| tst.js:49:6:49:6 | 1 |
| tst.ts:1:13:1:21 | <number>1 |
| tst.ts:1:21:1:21 | 1 |