Skip to content

Commit

Permalink
Use an index property on Position instead of the indexes WeakMap appr…
Browse files Browse the repository at this point in the history
…oach.

Reviewed by @tolmasky.
  • Loading branch information
tolmasky committed Jan 18, 2022
1 parent e6cc107 commit ad339d4
Show file tree
Hide file tree
Showing 9 changed files with 31 additions and 58 deletions.
7 changes: 3 additions & 4 deletions packages/babel-parser/src/parser/error.js
@@ -1,6 +1,6 @@
// @flow
/* eslint sort-keys: "error" */
import { type Position, indexes } from "../util/location";
import { type Position } from "../util/location";
import CommentsParser from "./comments";
import { type ErrorCode, ErrorCodes } from "./error-codes";
import { type Node } from "../types";
Expand Down Expand Up @@ -111,8 +111,7 @@ export default class ParserError extends CommentsParser {
{ code, template }: ErrorTemplate,
...params: any
): Error | empty {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
const pos: number = indexes.get(loc);
const pos = loc.index;
const message =
template.replace(/%(\d+)/g, (_, i: number) => params[i]) +
` (${loc.line}:${loc.column})`;
Expand All @@ -139,7 +138,7 @@ export default class ParserError extends CommentsParser {
errorTemplate: string,
...params: any
): Error | empty {
const pos = indexes.get(loc);
const pos = loc.index;
const message =
errorTemplate.replace(/%(\d+)/g, (_, i: number) => params[i]) +
` (${loc.line}:${loc.column})`;
Expand Down
17 changes: 5 additions & 12 deletions packages/babel-parser/src/parser/expression.js
Expand Up @@ -44,11 +44,7 @@ import {
isIdentifierStart,
canBeReservedWord,
} from "../util/identifier";
import {
indexes,
Position,
createPositionWithColumnOffset,
} from "../util/location";
import { Position, createPositionWithColumnOffset } from "../util/location";
import * as charCodes from "charcodes";
import {
BIND_OUTSIDE,
Expand Down Expand Up @@ -317,15 +313,13 @@ export default class ExpressionParser extends LValParser {

if (
refExpressionErrors.doubleProtoLoc != null &&
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
indexes.get(refExpressionErrors.doubleProtoLoc) >= startPos
refExpressionErrors.doubleProtoLoc.index >= startPos
) {
refExpressionErrors.doubleProtoLoc = null; // reset because double __proto__ is valid in assignment expression
}
if (
refExpressionErrors.shorthandAssignLoc != null &&
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
indexes.get(refExpressionErrors.shorthandAssignLoc) >= startPos
refExpressionErrors.shorthandAssignLoc.index >= startPos
) {
refExpressionErrors.shorthandAssignLoc = null; // reset because shorthand default was used correctly
}
Expand Down Expand Up @@ -918,7 +912,7 @@ export default class ExpressionParser extends LValParser {
return (
base.type === "Identifier" &&
base.name === "async" &&
indexes.get(this.state.lastTokEndLoc) === base.end &&
this.state.lastTokEndLoc.index === base.end &&
!this.canInsertSemicolon() &&
// check there are no escape sequences, such as \u{61}sync
base.end - base.start === 5 &&
Expand Down Expand Up @@ -1770,8 +1764,7 @@ export default class ExpressionParser extends LValParser {
this.takeSurroundingComments(
val,
startPos,
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
indexes.get(this.state.lastTokEndLoc),
this.state.lastTokEndLoc.index,
);

return val;
Expand Down
11 changes: 5 additions & 6 deletions packages/babel-parser/src/parser/node.js
Expand Up @@ -2,7 +2,7 @@

import type Parser from "./index";
import UtilParser from "./util";
import { indexes, type Position, SourceLocation } from "../util/location";
import { SourceLocation, type Position } from "../util/location";
import type { Comment, Node as NodeType, NodeBase } from "../types";

// Start an AST node, attaching a start offset.
Expand Down Expand Up @@ -126,9 +126,9 @@ export class NodeUtils extends UtilParser {
);
}
node.type = type;
node.end = indexes.get(endLoc);
node.end = endLoc.index;
node.loc.end = endLoc;
if (this.options.ranges) node.range[1] = node.end;
if (this.options.ranges) node.range[1] = endLoc.index;
if (this.options.attachComment) this.processComment(node);
return node;
}
Expand All @@ -143,10 +143,9 @@ export class NodeUtils extends UtilParser {
node: NodeBase,
endLoc?: Position = this.state.lastTokEndLoc,
): void {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
node.end = indexes.get(endLoc);
node.end = endLoc.index;
node.loc.end = endLoc;
if (this.options.ranges) node.range[1] = node.end;
if (this.options.ranges) node.range[1] = endLoc.index;
}

/**
Expand Down
7 changes: 3 additions & 4 deletions packages/babel-parser/src/parser/util.js
@@ -1,6 +1,6 @@
// @flow

import { indexes, type Position } from "../util/location";
import { type Position } from "../util/location";
import {
tokenIsLiteralPropertyName,
tokenLabelName,
Expand Down Expand Up @@ -120,7 +120,7 @@ export default class UtilParser extends Tokenizer {

hasPrecedingLineBreak(): boolean {
return lineBreak.test(
this.input.slice(indexes.get(this.state.lastTokEndLoc), this.state.start),
this.input.slice(this.state.lastTokEndLoc.index, this.state.start),
);
}

Expand Down Expand Up @@ -152,8 +152,7 @@ export default class UtilParser extends Tokenizer {

// Throws if the current token and the prev one are separated by a space.
assertNoSpace(message: string = "Unexpected space."): void {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
if (this.state.start > indexes.get(this.state.lastTokEndLoc)) {
if (this.state.start > this.state.lastTokEndLoc.index) {
/* eslint-disable @babel/development-internal/dry-error-messages */
this.raise(
{
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-parser/src/plugins/flow/index.js
Expand Up @@ -17,7 +17,7 @@ import {
tokenIsFlowInterfaceOrTypeOrOpaque,
} from "../../tokenizer/types";
import * as N from "../../types";
import { indexes, Position } from "../../util/location";
import { Position } from "../../util/location";
import { types as tc } from "../../tokenizer/context";
import * as charCodes from "charcodes";
import { isIteratorStart } from "../../util/identifier";
Expand Down Expand Up @@ -269,7 +269,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
this.next(); // eat `%`
this.expectContextual(tt._checks);
// Force '%' and 'checks' to be adjacent
if (this.state.lastTokStart > indexes.get(moduloLoc) + 1) {
if (this.state.lastTokStart > moduloLoc.index + 1) {
this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, {
at: moduloLoc,
});
Expand Down
5 changes: 2 additions & 3 deletions packages/babel-parser/src/plugins/jsx/index.js
Expand Up @@ -18,7 +18,7 @@ import {
import { TokContext, types as tc } from "../../tokenizer/context";
import * as N from "../../types";
import { isIdentifierChar, isIdentifierStart } from "../../util/identifier";
import { indexes, type Position } from "../../util/location";
import type { Position } from "../../util/location";
import { isNewLine } from "../../util/whitespace";
import { Errors, makeErrorTemplates, ErrorCodes } from "../../parser/error";

Expand Down Expand Up @@ -327,8 +327,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>

jsxParseEmptyExpression(): N.JSXEmptyExpression {
const node = this.startNodeAt(
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
indexes.get(this.state.lastTokEndLoc),
this.state.lastTokEndLoc.index,
this.state.lastTokEndLoc,
);
return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
Expand Down
17 changes: 5 additions & 12 deletions packages/babel-parser/src/tokenizer/index.js
Expand Up @@ -3,11 +3,7 @@
/*:: declare var invariant; */

import type { Options } from "../options";
import {
indexes,
Position,
createPositionWithColumnOffset,
} from "../util/location";
import { Position, createPositionWithColumnOffset } from "../util/location";
import * as N from "../types";
import * as charCodes from "charcodes";
import { isIdentifierStart, isIdentifierChar } from "../util/identifier";
Expand Down Expand Up @@ -1253,7 +1249,7 @@ export default class Tokenizer extends ParserErrors {

if (isBigInt) {
const str = this.input
.slice(indexes.get(startLoc), this.state.pos)
.slice(startLoc.index, this.state.pos)
.replace(/[_n]/g, "");
this.finishToken(tt.bigint, str);
return;
Expand Down Expand Up @@ -1498,12 +1494,10 @@ export default class Tokenizer extends ParserErrors {
}

recordStrictModeErrors(message: ErrorTemplate, loc: Position) {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
const index: number = indexes.get(loc);
if (this.state.strict && !this.state.strictErrors.has(index)) {
if (this.state.strict && !this.state.strictErrors.has(loc.index)) {
this.raise(message, { at: loc });
} else {
this.state.strictErrors.set(index, { loc, message });
this.state.strictErrors.set(loc.index, { loc, message });
}
}

Expand Down Expand Up @@ -1613,8 +1607,7 @@ export default class Tokenizer extends ParserErrors {
if (throwOnInvalid) {
this.raise(Errors.InvalidEscapeSequence, { at: codeLoc });
} else {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
this.state.pos = indexes.get(codeLoc) - 1;
this.state.pos = codeLoc.index - 1;
}
}
return n;
Expand Down
8 changes: 3 additions & 5 deletions packages/babel-parser/src/util/expression-scope.js
@@ -1,7 +1,7 @@
// @flow

import type { ErrorData, ErrorTemplate, raiseFunction } from "../parser/error";
import { indexes, Position } from "./location";
import { Position } from "./location";

/*:: declare var invariant; */
/**
Expand Down Expand Up @@ -80,12 +80,10 @@ class ArrowHeadParsingScope extends ExpressionScope {
super(type);
}
recordDeclarationError(message: ErrorTemplate, loc: Position) {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
this.errors.set(indexes.get(loc), { message, loc });
this.errors.set(loc.index, { message, loc });
}
clearDeclarationError(loc: Position) {
// $FlowIgnore[incompatible-type] We know this exists, so it can't be undefined.
this.errors.delete(indexes.get(loc));
this.errors.delete(loc.index);
}
iterateErrors(iterator: (data: ErrorData) => void) {
this.errors.forEach(iterator);
Expand Down
13 changes: 3 additions & 10 deletions packages/babel-parser/src/util/location.js
Expand Up @@ -17,8 +17,7 @@ export class Position {
this.column = col;

// this.index = index;
// Object.defineProperty(this, "index", { enumerable: false, value: index });
indexes.set(this, index);
Object.defineProperty(this, "index", { enumerable: false, value: index });
}
}

Expand All @@ -35,8 +34,6 @@ export class SourceLocation {
}
}

export const indexes: WeakMap<Position, number> = new WeakMap();

/**
* creates a new position with a non-zero column offset from the given position.
* This function should be only be used when we create AST node out of the token
Expand All @@ -52,10 +49,6 @@ export function createPositionWithColumnOffset(
position: Position,
columnOffset: number,
) {
const { line, column } = position;
return new Position(
line,
column + columnOffset,
indexes.get(position) + columnOffset,
);
const { line, column, index } = position;
return new Position(line, column + columnOffset, index + columnOffset);
}

0 comments on commit ad339d4

Please sign in to comment.