Skip to content

Commit

Permalink
Only compute Position if not already in state (#9989)
Browse files Browse the repository at this point in the history
* Only compute Position if not already in state

* Prioritize start locations
  • Loading branch information
danez committed May 17, 2019
1 parent 2080042 commit b1826bf
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
14 changes: 13 additions & 1 deletion packages/babel-parser/src/parser/location.js
Expand Up @@ -10,6 +10,17 @@ import CommentsParser from "./comments";
// message.

export default class LocationParser extends CommentsParser {
getLocationForPosition(pos: number): Position {
let loc;
if (pos === this.state.start) loc = this.state.startLoc;
else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;
else if (pos === this.state.end) loc = this.state.endLoc;
else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;
else loc = getLineInfo(this.input, pos);

return loc;
}

raise(
pos: number,
message: string,
Expand All @@ -21,7 +32,8 @@ export default class LocationParser extends CommentsParser {
code?: string,
} = {},
): empty {
const loc = getLineInfo(this.input, pos);
const loc = this.getLocationForPosition(pos);

message += ` (${loc.line}:${loc.column})`;
// $FlowIgnore
const err: SyntaxError & { pos: number, loc: Position } = new SyntaxError(
Expand Down
38 changes: 38 additions & 0 deletions packages/babel-parser/test/unit/util/location.js
@@ -0,0 +1,38 @@
import { getLineInfo } from "../../../src/util/location";

describe("getLineInfo", () => {
const input = "a\nb\nc\nd\ne\nf\ng\nh\ni";

it("reports correct position", () => {
expect(getLineInfo(input, 7)).toEqual({
column: 1,
line: 4,
});
});

it("reports correct position for first line", () => {
expect(getLineInfo(input, 0)).toEqual({
column: 0,
line: 1,
});
});

const inputArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const singleCharLineEndings = ["\n", "\r", "\u2028", "\u2029"];

singleCharLineEndings.forEach(ending => {
it(`supports ${escape(ending)} line ending`, () => {
expect(getLineInfo(inputArray.join(ending), 7)).toEqual({
column: 1,
line: 4,
});
});
});

it(`supports ${escape("\r\n")} line ending`, () => {
expect(getLineInfo(inputArray.join("\r\n"), 7)).toEqual({
column: 1,
line: 3,
});
});
});

0 comments on commit b1826bf

Please sign in to comment.