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<T>` 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.
This commit is contained in:
parent
e4bcd1d0ff
commit
55d5545614
@ -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;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user