From 344c03b2e64af9caa0e386a63476805831a8e0b0 Mon Sep 17 00:00:00 2001 From: Mestery Date: Thu, 23 Sep 2021 19:51:31 +0200 Subject: [PATCH] repl: skip EmptyStatements and return result with TLA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: https://github.com/nodejs/node/issues/39932 PR-URL: https://github.com/nodejs/node/pull/40194 Reviewed-By: Antoine du Hamel Reviewed-By: James M Snell Reviewed-By: Michaƫl Zasso --- lib/internal/repl/await.js | 36 ++++++++++--------- .../test-repl-preprocess-top-level-await.js | 2 ++ 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/lib/internal/repl/await.js b/lib/internal/repl/await.js index ba138fdfe8c8d9..ec1d0c8823e107 100644 --- a/lib/internal/repl/await.js +++ b/lib/internal/repl/await.js @@ -221,22 +221,26 @@ function processTopLevelAwait(src) { return null; } - const last = body.body[body.body.length - 1]; - if (last.type === 'ExpressionStatement') { - // For an expression statement of the form - // ( expr ) ; - // ^^^^^^^^^^ // last - // ^^^^ // last.expression - // - // We do not want the left parenthesis before the `return` keyword; - // therefore we prepend the `return (` to `last`. - // - // On the other hand, we do not want the right parenthesis after the - // semicolon. Since there can only be more right parentheses between - // last.expression.end and the semicolon, appending one more to - // last.expression should be fine. - state.prepend(last, 'return ('); - state.append(last.expression, ')'); + for (let i = body.body.length - 1; i >= 0; i--) { + const node = body.body[i]; + if (node.type === 'EmptyStatement') continue; + if (node.type === 'ExpressionStatement') { + // For an expression statement of the form + // ( expr ) ; + // ^^^^^^^^^^ // node + // ^^^^ // node.expression + // + // We do not want the left parenthesis before the `return` keyword; + // therefore we prepend the `return (` to `node`. + // + // On the other hand, we do not want the right parenthesis after the + // semicolon. Since there can only be more right parentheses between + // node.expression.end and the semicolon, appending one more to + // node.expression should be fine. + state.prepend(node, 'return ('); + state.append(node.expression, ')'); + } + break; } return ( diff --git a/test/parallel/test-repl-preprocess-top-level-await.js b/test/parallel/test-repl-preprocess-top-level-await.js index 656b616b71d9e6..51b15e107f53bc 100644 --- a/test/parallel/test-repl-preprocess-top-level-await.js +++ b/test/parallel/test-repl-preprocess-top-level-await.js @@ -22,6 +22,8 @@ const testCases = [ `(async () => { return (await ${surrogate}) })()` ], [ 'await 0;', '(async () => { return (await 0); })()' ], + [ 'await 0;;;', + '(async () => { return (await 0);;; })()' ], [ `await ${surrogate};`, `(async () => { return (await ${surrogate}); })()` ], [ `await ${surrogate};`,