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

Implement optional chaining deletion #492

Merged
merged 1 commit into from
Dec 29, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/HelperManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ const HELPERS = {
return value;
}
`,
optionalChainDelete: `
function optionalChainDelete(ops) {
const result = OPTIONAL_CHAIN_NAME(ops);
return result == null ? true : result;
}
`,
};

export class HelperManager {
Expand All @@ -95,8 +101,15 @@ export class HelperManager {

emitHelpers(): string {
let resultCode = "";
for (const [baseName, helperCode] of Object.entries(HELPERS)) {
if (this.helperNames.optionalChainDelete) {
this.getHelperName("optionalChain");
}
for (const [baseName, helperCodeTemplate] of Object.entries(HELPERS)) {
const helperName = this.helperNames[baseName];
let helperCode = helperCodeTemplate;
if (baseName === "optionalChainDelete") {
helperCode = helperCode.replace("OPTIONAL_CHAIN_NAME", this.helperNames.optionalChain!);
}
if (helperName) {
resultCode += " ";
resultCode += helperCode
Expand Down
6 changes: 5 additions & 1 deletion src/TokenProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,11 @@ export default class TokenProcessor {
}
}
if (token.isOptionalChainStart) {
this.resultCode += this.helperManager.getHelperName("optionalChain");
if (this.tokenIndex > 0 && this.tokenAtRelativeIndex(-1).type === tt._delete) {
this.resultCode += this.helperManager.getHelperName("optionalChainDelete");
} else {
this.resultCode += this.helperManager.getHelperName("optionalChain");
}
this.resultCode += "([";
}
}
Expand Down
69 changes: 59 additions & 10 deletions src/transformers/OptionalChainingNullishTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,78 @@ export default class OptionalChainingNullishTransformer extends Transformer {
this.tokens.replaceTokenTrimmingLeftWhitespace(", () =>");
return true;
}
if (this.tokens.matches1(tt._delete)) {
const nextToken = this.tokens.tokenAtRelativeIndex(1);
if (nextToken.isOptionalChainStart) {
this.tokens.removeInitialToken();
return true;
}
}
const token = this.tokens.currentToken();
if (
token.subscriptStartIndex != null &&
this.tokens.tokens[token.subscriptStartIndex].isOptionalChainStart
) {
const chainStart = token.subscriptStartIndex;
if (chainStart != null && this.tokens.tokens[chainStart].isOptionalChainStart) {
const param = this.nameManager.claimFreeName("_");
let arrowStartSnippet;
if (
chainStart > 0 &&
this.tokens.matches1AtIndex(chainStart - 1, tt._delete) &&
this.isLastSubscriptInChain()
) {
// Delete operations are special: we already removed the delete keyword, and to still
// perform a delete, we need to insert a delete in the very last part of the chain, which
// in correct code will always be a property access.
arrowStartSnippet = `${param} => delete ${param}`;
} else {
arrowStartSnippet = `${param} => ${param}`;
}
if (this.tokens.matches2(tt.questionDot, tt.parenL)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${param} => ${param}`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${arrowStartSnippet}`);
} else if (this.tokens.matches2(tt.questionDot, tt.bracketL)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${param} => ${param}`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}`);
} else if (this.tokens.matches1(tt.questionDot)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${param} => ${param}.`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}.`);
} else if (this.tokens.matches1(tt.dot)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${param} => ${param}.`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}.`);
} else if (this.tokens.matches1(tt.bracketL)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${param} => ${param}[`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}[`);
} else if (this.tokens.matches1(tt.parenL)) {
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${param} => ${param}(`);
this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${arrowStartSnippet}(`);
} else {
throw new Error("Unexpected subscript operator in optional chain.");
}
return true;
}
return false;
}

/**
* Determine if the current token is the last of its chain, so that we know whether it's eligible
* to have a delete op inserted.
*
* We can do this by walking forward until we determine one way or another. Each
* isOptionalChainStart token must be paired with exactly one isOptionalChainEnd token after it in
* a nesting way, so we can track depth and walk to the end of the chain (the point where the
* depth goes negative) and see if any other subscript token is after us in the chain.
*/
isLastSubscriptInChain(): boolean {
let depth = 0;
for (let i = this.tokens.currentIndex() + 1; ; i++) {
if (i >= this.tokens.tokens.length) {
throw new Error("Reached the end of the code while finding the end of the access chain.");
}
if (this.tokens.tokens[i].isOptionalChainStart) {
depth++;
} else if (this.tokens.tokens[i].isOptionalChainEnd) {
depth--;
}
if (depth < 0) {
return true;
}

// This subscript token is a later one in the same chain.
if (depth === 0 && this.tokens.tokens[i].subscriptStartIndex != null) {
return false;
}
}
}
}
2 changes: 2 additions & 0 deletions test/prefixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value =
else if (op === 'call' || op === 'optionalCall') { \
value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; \
} } return value; }`;
export const OPTIONAL_CHAIN_DELETE_PREFIX = ` function _optionalChainDelete(ops) { \
const result = _optionalChain(ops); return result == null ? true : result; }`;
51 changes: 50 additions & 1 deletion test/sucrase-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ESMODULE_PREFIX,
IMPORT_DEFAULT_PREFIX,
NULLISH_COALESCE_PREFIX,
OPTIONAL_CHAIN_DELETE_PREFIX,
OPTIONAL_CHAIN_PREFIX,
} from "./prefixes";
import {assertOutput, assertResult} from "./util";
Expand Down Expand Up @@ -913,7 +914,7 @@ describe("sucrase", () => {
);
});

it("handles nested optional chain operations", () => {
it("handles nested nullish coalescing operations", () => {
assertOutput(
`
setOutput(undefined ?? 7 ?? null);
Expand Down Expand Up @@ -976,4 +977,52 @@ describe("sucrase", () => {
{transforms: []},
);
});

it("transpiles optional chain deletion", () => {
assertResult(
`
delete a?.b.c;
`,
`${OPTIONAL_CHAIN_PREFIX}${OPTIONAL_CHAIN_DELETE_PREFIX}
_optionalChainDelete([a, 'optionalAccess', _ => _.b, 'access', _2 => delete _2.c]);
`,
{transforms: []},
);
});

it("correctly identifies last element of optional chain deletion", () => {
assertResult(
`
delete a?.b[c?.c];
`,
`${OPTIONAL_CHAIN_PREFIX}${OPTIONAL_CHAIN_DELETE_PREFIX}
_optionalChainDelete([a, 'optionalAccess', _ => _.b, 'access', _2 => delete _2[_optionalChain([c, 'optionalAccess', _3 => _3.c])]]);
`,
{transforms: []},
);
});

it("deletes the property correctly with optional chain deletion", () => {
assertOutput(
`
const o = {x: 1};
delete o?.x;
setOutput(o.hasOwnProperty('x'))
`,
false,
{transforms: []},
);
});

it("does not crash with optional chain deletion on null", () => {
assertOutput(
`
const o = null;
delete o?.x;
setOutput(o)
`,
null,
{transforms: []},
);
});
});