@@ -9,7 +9,7 @@ import ts from 'typescript';
99 *
1010 * to:
1111 *
12- * ( <cond>) || invariant(false ...)
12+ * if (!( <cond>)) invariant(false, ...)
1313 */
1414export function inlineInvariant ( context : ts . TransformationContext ) {
1515 const { factory } = context ;
@@ -21,25 +21,38 @@ export function inlineInvariant(context: ts.TransformationContext) {
2121 }
2222
2323 function visitNode ( node : ts . Node ) : ts . Node {
24- if ( ts . isCallExpression ( node ) ) {
25- const { expression, arguments : args } = node ;
26-
27- if ( ts . isIdentifier ( expression ) && args . length > 0 ) {
28- const funcName = expression . escapedText ;
29- if ( funcName === 'invariant' || funcName === 'devAssert' ) {
30- const [ condition , ...otherArgs ] = args ;
31-
32- return factory . createBinaryExpression (
33- factory . createParenthesizedExpression ( condition ) ,
34- ts . SyntaxKind . BarBarToken ,
35- factory . createCallExpression ( expression , undefined , [
36- factory . createFalse ( ) ,
37- ...otherArgs ,
38- ] ) ,
39- ) ;
24+ if ( ts . isExpressionStatement ( node ) ) {
25+ const expression = node . expression ;
26+
27+ if ( ts . isCallExpression ( expression ) ) {
28+ const { arguments : args } = expression ;
29+
30+ if ( ts . isIdentifier ( expression . expression ) && args . length > 0 ) {
31+ const funcName = expression . expression . escapedText ;
32+ if ( funcName === 'invariant' || funcName === 'devAssert' ) {
33+ const [ condition , ...otherArgs ] = args ;
34+ if ( condition . kind === ts . SyntaxKind . FalseKeyword ) {
35+ return node ;
36+ }
37+ const inverseCondition = factory . createPrefixUnaryExpression (
38+ ts . SyntaxKind . ExclamationToken ,
39+ factory . createParenthesizedExpression ( condition ) ,
40+ ) ;
41+
42+ return factory . createIfStatement (
43+ inverseCondition ,
44+ factory . createExpressionStatement (
45+ factory . createCallExpression ( expression . expression , undefined , [
46+ factory . createFalse ( ) ,
47+ ...otherArgs ,
48+ ] ) ,
49+ ) ,
50+ ) ;
51+ }
4052 }
4153 }
4254 }
55+
4356 return ts . visitEachChild ( node , visitNode , context ) ;
4457 }
4558}
0 commit comments