Skip to content

cell destructuring #88

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 1 addition & 2 deletions src/features.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ import {simple} from "acorn-walk";
import walk from "./walk.js";

export default function findFeatures(cell, featureName) {
const ast = {type: "Program", body: [cell.body]};
const features = new Map();
const {references} = cell;

simple(
ast,
cell,
{
CallExpression: node => {
const {callee, arguments: args} = node;
Expand Down
198 changes: 178 additions & 20 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export function parseCell(input, {tag, raw, globals, ...options} = {}) {
}
parseReferences(cell, input, globals);
parseFeatures(cell, input);
parseDeclarations(cell);
return cell;
}

Expand Down Expand Up @@ -133,8 +134,15 @@ export class CellParser extends Parser {

// A non-empty cell?
else if (token.type !== tt.eof && token.type !== tt.semi) {
// A named cell?
if (token.type === tt.name) {

// A destructuring cell, or parenthesized expression? (A destructuring
// cell is a parenthesized expression followed by the equals operator.)
if (token.type === tt.parenL) {
({id, body} = this.parseParenAndDistinguishCell());
}

// A simple named cell?
else if (token.type === tt.name) {
if (token.value === "viewof" || token.value === "mutable") {
token = lookahead.getToken();
if (token.type !== tt.name) {
Expand All @@ -152,22 +160,20 @@ export class CellParser extends Parser {
}
}

// A block?
if (token.type === tt.braceL) {
body = this.parseBlock();
// A block or non-parenthesized expression?
if (body === null) {
body = token.type === tt.braceL
? this.parseBlock()
: this.parseExpression();
}

// An expression?
// Possibly a function or class declaration?
else {
body = this.parseExpression();
if (
id === null &&
(body.type === "FunctionExpression" ||
body.type === "ClassExpression")
) {
id = body.id;
}
// Promote the name of a function or class declaration?
if (
id === null &&
(body.type === "FunctionExpression" ||
body.type === "ClassExpression")
) {
id = body.id;
}
}

Expand All @@ -176,6 +182,99 @@ export class CellParser extends Parser {

return this.finishCell(node, body, id);
}
// Adapted from parseParenAndDistinguishExpression
parseParenAndDistinguishCell() {
let startPos = this.start,
startLoc = this.startLoc,
val;

this.next();

let innerStartPos = this.start,
innerStartLoc = this.startLoc,
exprList = [],
first = true,
lastIsComma = false,
refDestructuringErrors = new DestructuringErrors,
oldYieldPos = this.yieldPos,
oldAwaitPos = this.awaitPos,
spreadStart;

this.yieldPos = 0;
this.awaitPos = 0;

// Do not save awaitIdentPos to allow checking awaits nested in parameters
while (this.type !== tt.parenR) {
first ? first = false : this.expect(tt.comma);
if (this.afterTrailingComma(tt.parenR, true)) {
lastIsComma = true;
break;
} else if (this.type === tt.ellipsis) {
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRestBinding()));
if (this.type === tt.comma) this.raise(this.start, "Comma is not permitted after the rest element");
break;
} else {
exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
}
}

let innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
this.expect(tt.parenR);

if (!this.canInsertSemicolon()) {
if (this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return {
id: null,
body: this.parseParenArrowList(startPos, startLoc, exprList)
};
}
if (this.eat(tt.eq)) {
if (exprList.length !== 1 || lastIsComma) this.unexpected(this.lastTokStart);
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;

val = this.parseParenArrowList(startPos, startLoc, exprList);

// Don’t allow destructuring into viewof or mutable declarations.
declarePattern(val.params[0], id => {
if (id.type !== "Identifier") {
this.unexpected(id.start);
}
});

return {
id: val.params[0],
body: val.body
};
}
}

if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart);
if (spreadStart) this.unexpected(spreadStart);
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;

if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}

return {
id: null,
body: val
};
}
parseTopLevel(node) {
return this.parseCell(node, true);
}
Expand Down Expand Up @@ -204,10 +303,8 @@ export class CellParser extends Parser {
);
}
unexpected(pos) {
this.raise(
pos != null ? pos : this.start,
this.type === tt.eof ? "Unexpected end of input" : "Unexpected token"
);
if (pos == null) pos = this.start;
this.raise(pos, pos === this.input.length ? "Unexpected end of input" : "Unexpected token");
}
parseMaybeKeywordExpression(keyword, type) {
if (this.isContextual(keyword)) {
Expand All @@ -230,6 +327,14 @@ const o_tmpl = new TokContext(
parser => readTemplateToken.call(parser) // override
);

function DestructuringErrors() {
this.shorthandAssign =
this.trailingComma =
this.parenthesizedAssign =
this.parenthesizedBind =
this.doubleProto = -1;
}

export class TemplateCellParser extends CellParser {
constructor(...args) {
super(...args);
Expand Down Expand Up @@ -384,3 +489,56 @@ function parseFeatures(cell, input) {
}
return cell;
}

// Find declarations: things that this cell defines.
function parseDeclarations(cell) {
if (!cell.body) {
cell.declarations = [];
} else if (cell.body.type === "ImportDeclaration") {
cell.declarations = cell.body.specifiers.map(s => s.local);
} else if (!cell.id) {
cell.declarations = [];
} else {
switch (cell.id.type) {
case "Identifier":
case "ViewExpression":
case "MutableExpression":
cell.declarations = [cell.id];
break;
case "ArrayPattern":
case "ObjectPattern":
cell.declarations = [];
declarePattern(cell.id, node => cell.declarations.push(node));
break;
default:
throw new Error(`unexpected identifier: ${cell.id.type}`);
}
}
}

function declarePattern(node, callback) {
switch (node.type) {
case "Identifier":
case "ViewExpression":
case "MutableExpression":
callback(node);
break;
case "ObjectPattern":
node.properties.forEach(node => declarePattern(node, callback));
break;
case "ArrayPattern":
node.elements.forEach(node => node && declarePattern(node, callback));
break;
case "Property":
declarePattern(node.value, callback);
break;
case "RestElement":
declarePattern(node.argument, callback);
break;
case "AssignmentPattern":
declarePattern(node.left, callback);
break;
default:
throw new Error(`unexpected declaration: ${node.type}`);
}
}
27 changes: 22 additions & 5 deletions src/references.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ function declaresArguments(node) {
}

export default function findReferences(cell, globals) {
const ast = {type: "Program", body: [cell.body]};
const locals = new Map;
const globalSet = new Set(globals);
const references = [];
Expand Down Expand Up @@ -81,11 +80,11 @@ export default function findReferences(cell, globals) {
}

function declareModuleSpecifier(node) {
declareLocal(ast, node.local);
declareLocal(cell.body, node.local);
}

ancestor(
ast,
cell.body,
{
VariableDeclaration: (node, parents) => {
let parent = null;
Expand Down Expand Up @@ -154,8 +153,26 @@ export default function findReferences(cell, globals) {
}
}

function assignmentIdentifier(node, parents) {
if (parents.length > 2 && parents[1].type === "AssignmentPattern" && parents[2] === parents[1].right) {
identifier(node, parents);
}
}

if (cell.id && (cell.id.type === "ArrayPattern" || cell.id.type === "ObjectPattern")) {
declarePattern(cell.id, cell.id);
ancestor(
cell.id,
{
VariablePattern: assignmentIdentifier,
Identifier: assignmentIdentifier
},
walk
);
}

ancestor(
ast,
cell.body,
{
VariablePattern: identifier,
Identifier: identifier
Expand Down Expand Up @@ -210,7 +227,7 @@ export default function findReferences(cell, globals) {
}

ancestor(
ast,
cell.body,
{
AssignmentExpression: checkConstLeft,
AssignmentPattern: checkConstLeft,
Expand Down
8 changes: 7 additions & 1 deletion src/walk.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import {make} from "acorn-walk";

export default make({
Import() {},
Cell(node, st, c) {
if (node.id) c(node.id, st);
c(node.body, st);
},
CellTag(node, st, c) {
c(node.body, st);
},
ViewExpression(node, st, c) {
c(node.id, st, "Identifier");
},
Expand Down
1 change: 1 addition & 0 deletions test/input/arrow-function-expression.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x]) => { return [x]; } = 2
1 change: 1 addition & 0 deletions test/input/destructure-array-literal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([foo, ...bar]) = [1, 2, 3]
3 changes: 3 additions & 0 deletions test/input/destructure-block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
({foo, bar}) = {
return {foo: 1, bar: 2};
}
1 change: 1 addition & 0 deletions test/input/destructure-computed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({["foo"]}) = 42
1 change: 1 addition & 0 deletions test/input/destructure-default-value-async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x, y = x + await z]) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-default-value-reference.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x, y = x + z]) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-default-value-secret.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x, y = Secret("foo")]) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-default-value-yield.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x, y = x + yield z]) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-default-value.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x, y = 2]) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-dynamic-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({default: confetti}) = import("https://cdn.skypack.dev/canvas-confetti")
1 change: 1 addition & 0 deletions test/input/destructure-keyword.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([mutable]) = [42]
1 change: 1 addition & 0 deletions test/input/destructure-multiple.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x], y) = [1]
1 change: 1 addition & 0 deletions test/input/destructure-mutable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([mutable foo]) = [42]
1 change: 1 addition & 0 deletions test/input/destructure-nested-object-literal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({foo: {bar: {baz: qux}}}) = ({})
1 change: 1 addition & 0 deletions test/input/destructure-object-default-value.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({x, y = 2}) = ({x: 1})
1 change: 1 addition & 0 deletions test/input/destructure-object-literal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({foo, bar}) = ({foo: 1, bar: 2})
1 change: 1 addition & 0 deletions test/input/destructure-trailing-comma.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
([x], ) = [1]
1 change: 1 addition & 0 deletions test/input/named-with-parens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(foo) = 42
1 change: 1 addition & 0 deletions test/input/object-literal-async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({foo: await 42})
1 change: 1 addition & 0 deletions test/input/object-literal-yield.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
({foo: yield 42})
1 change: 1 addition & 0 deletions test/input/parenthesized-named-function.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(function foo() { return 42; })
3 changes: 2 additions & 1 deletion test/output/anonymous-block-cell.js.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@
"references": [],
"fileAttachments": [],
"databaseClients": [],
"secrets": []
"secrets": [],
"declarations": []
}
3 changes: 2 additions & 1 deletion test/output/anonymous-expression-cell.js.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"references": [],
"fileAttachments": [],
"databaseClients": [],
"secrets": []
"secrets": [],
"declarations": []
}
Loading