Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only compute Position if not already in state #9989

Merged
merged 2 commits into from May 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
});
});
});