From 55d5545614782ee87de47cd8be6898ef91d95c97 Mon Sep 17 00:00:00 2001 From: Benedikt Meurer Date: Sat, 28 Oct 2017 22:07:28 +0200 Subject: [PATCH] Fix "-1" array accesses in CommentsParser. (#777) Similar to the fixes in https://github.com/babel/babel/pull/6580 and https://github.com/babel/babel/pull/6581, accesses of the form ```js stack[stack.length - 1]; ``` when `stack` can be an empty array are pretty bad for performance. In this case it also breaks the type safety, since the function `last` is declared to only return values of type `T`, but occasionally also returns `undefined` now, since the `stack` parameters passed to it never contain a property `"-1"` and neither do the `Object.prototype` or the `Array.prototype`. This is a non-breaking performance fix, which adds proper checking to ensure that `last` is only invoked on non-empty arrays. --- src/parser/comments.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/parser/comments.js b/src/parser/comments.js index b3d4925927..6bc7e2b2f9 100644 --- a/src/parser/comments.js +++ b/src/parser/comments.js @@ -65,14 +65,15 @@ export default class CommentsParser extends BaseParser { this.state.trailingComments.length = 0; } } else { - const lastInStack = last(stack); - if ( - stack.length > 0 && - lastInStack.trailingComments && - lastInStack.trailingComments[0].start >= node.end - ) { - trailingComments = lastInStack.trailingComments; - lastInStack.trailingComments = null; + if (stack.length > 0) { + const lastInStack = last(stack); + if ( + lastInStack.trailingComments && + lastInStack.trailingComments[0].start >= node.end + ) { + trailingComments = lastInStack.trailingComments; + lastInStack.trailingComments = null; + } } } @@ -138,6 +139,7 @@ export default class CommentsParser extends BaseParser { if (lastChild.leadingComments) { if ( lastChild !== node && + lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start ) { node.leadingComments = lastChild.leadingComments;