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

Refactoring sqPath #2986

Merged
merged 22 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Further cleanup
  • Loading branch information
OAGr committed Jan 20, 2024
commit 84e17788e0e0a0be022083ac5e6864e4d329c6ad
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const FocusedNavigation: FC<{
)}

{focusedPath
.itemsAsValuePaths({ includeRoot: false })
.allSqValuePathSubsets({ includeRoot: false })
.slice(rootPathFocusedAdjustment, -1)
.map((path, i) => (
<FocusedNavigationItem
Expand Down
19 changes: 9 additions & 10 deletions packages/components/src/components/SquiggleViewer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function pathToShortName(path: SqValuePath): string {
if (path.isRoot()) {
return topLevelName(path);
} else {
return path.lastItem().toDisplayString();
return path.lastItem()!.toDisplayString();
}
}

Expand Down Expand Up @@ -55,25 +55,24 @@ export function useGetSubvalueByPath() {
}

let currentValue = topValue;
const subValuePaths = subValuePath.itemsAsValuePaths({
const subValuePaths = subValuePath.allSqValuePathSubsets({
includeRoot: false,
});

for (const subValuePath of subValuePaths) {
const pathItem = subValuePath.lastItem();
const pathItem = subValuePath.lastItem()!; // We know it's not empty, because includeRoot is false.
const currentTag = currentValue.tag;
const pathItemType = pathItem.value.type;

let nextValue: SqValue | undefined;

if (currentValue.tag === "Array" && pathItem.value.type === "number") {
if (currentTag === "Array" && pathItemType === "number") {
nextValue = currentValue.value.getValues()[pathItem.value.value];
} else if (
currentValue.tag === "Dict" &&
pathItem.value.type === "string"
) {
} else if (currentTag === "Dict" && pathItemType === "string") {
nextValue = currentValue.value.get(pathItem.value.value);
} else if (
currentValue.tag === "TableChart" &&
pathItem.value.type === "cellAddress"
currentTag === "TableChart" &&
pathItemType === "cellAddress"
) {
// Maybe it would be better to get the environment in a different way.
const environment = context.project.getEnvironment();
Expand Down
25 changes: 0 additions & 25 deletions packages/squiggle-lang/__tests__/public/SqValuePath_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,6 @@ describe("SqValuePath", () => {
],
});

describe("serializeToString() and deserialize()", () => {
test("Works on complex paths", () => {
const complexPath = new SqValuePath({
root: "exports",
items: [
SqPathItem.fromString("nested"),
SqPathItem.fromNumber(42),
SqPathItem.fromCellAddress(5, 10),
],
});
const serialized = complexPath.serializeToString();
const deserialized = SqValuePath.deserialize(serialized);
expect(deserialized).toEqual(complexPath);
});
test("works on empty path", () => {
const emptyPath = new SqValuePath({ root: "imports", items: [] });
const serialized = emptyPath.serializeToString();
const deserialized = SqValuePath.deserialize(serialized);
expect(deserialized.items.length).toBe(0);
});
test("throws error on invalid input", () => {
expect(() => SqValuePath.deserialize("invalid")).toThrow(Error);
});
});

test("isEqual()", () => {
const path2 = new SqValuePath({
root: "bindings",
Expand Down
2 changes: 1 addition & 1 deletion packages/squiggle-lang/src/public/SqProject/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ export class SqProject {
if (!ast.ok) {
return ast;
}
const found = SqValuePath.findByOffset({
const found = SqValuePath.findByAstOffset({
ast: ast.value,
offset,
});
Expand Down
213 changes: 102 additions & 111 deletions packages/squiggle-lang/src/public/SqValuePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,85 @@ export class SqPathItem {
return "calculator";
}
}
}

serialize(): string {
return JSON.stringify(this.value);
}
// There might be a better place for this to go, nearer to the ASTNode type.
function astOffsetToPathItems(ast: ASTNode, offset: number): SqPathItem[] {
function buildRemainingPathItems(ast: ASTNode): SqPathItem[] {
switch (ast.type) {
case "Program": {
for (const statement of ast.statements) {
if (locationContains(statement.location, offset)) {
return buildRemainingPathItems(statement);
}
}
return [];
}
case "Dict": {
for (const pair of ast.elements) {
if (
!locationContains(
{
source: ast.location.source,
start: pair.location.start,
end: pair.location.end,
},
offset
)
) {
continue;
}

static deserialize(str: string): SqPathItem {
const value = JSON.parse(str) as PathItem;
return new SqPathItem(value);
if (
pair.type === "KeyValue" &&
pair.key.type === "String" // only string keys are supported
) {
return [
SqPathItem.fromString(pair.key.value),
...buildRemainingPathItems(pair.value),
];
} else if (pair.type === "Identifier") {
return [SqPathItem.fromString(pair.value)]; // this is a final node, no need to buildRemainingPathItems recursively
}
}
return [];
}
case "Array": {
for (let i = 0; i < ast.elements.length; i++) {
const element = ast.elements[i];
if (locationContains(element.location, offset)) {
return [
SqPathItem.fromNumber(i),
...buildRemainingPathItems(element),
];
}
}
return [];
}
case "LetStatement": {
return [
SqPathItem.fromString(ast.variable.value),
...buildRemainingPathItems(ast.value),
];
}
case "DefunStatement": {
return [
SqPathItem.fromString(ast.variable.value),
...buildRemainingPathItems(ast.value),
];
}
case "Block": {
if (
ast.statements.length === 1 &&
["Array", "Dict"].includes(ast.statements[0].type)
) {
return buildRemainingPathItems(ast.statements[0]);
}
}
}
return [];
}
return buildRemainingPathItems(ast);
}

export class SqValuePath {
Expand All @@ -90,7 +160,24 @@ export class SqValuePath {
this.items = props.items;
}

lastItem() {
static findByAstOffset({
ast,
offset,
}: {
ast: ASTNode;
offset: number;
}): SqValuePath | undefined {
return new SqValuePath({
root: "bindings", // not important, will probably be removed soon
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thoughts on this old comment:

  • I don't believe anymore that we'll remove the root info here, it's important
  • viewValuePath in ViewerProvider is currently broken when "Result" or "Imports" tab is selected, or even "Exports"; we should switch the dropdown to "Variables" when "Find in viewer" hotkey is pressed, and be more clever about "Exports" (maybe you already noticed this when you added gutter circles)
  • we could implement "find in editor" on imports, but we'd have to switch the viewer to "Imports" tab, and I'm not sure if it's worth it since we'll also get tooltips soon

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm... makes sense. I'd like to fix this if it's not too much work - for keyboard navigation and stuff to work well. Will see though, later. lots to do.

items: astOffsetToPathItems(ast, offset),
});
}

isRoot() {
return this.items.length === 0;
}

lastItem(): SqPathItem | undefined {
return this.items[this.items.length - 1];
}

Expand All @@ -101,7 +188,11 @@ export class SqValuePath {
});
}

// Checks if this SqValuePath completely contains all of the nodes in this other one.
contains(smallerItem: SqValuePath) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startsWith(prefix: SqValuePath)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about hasAsPrefix or hasPrefix

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That works too. I suggested startsWith because of String.startsWith.

if (this.root !== smallerItem.root) {
return false;
}
if (this.items.length < smallerItem.items.length) {
return false;
}
Expand All @@ -114,6 +205,9 @@ export class SqValuePath {
}

isEqual(other: SqValuePath) {
if (this.root !== other.root) {
return false;
}
if (this.items.length !== other.items.length) {
return false;
}
Expand All @@ -125,21 +219,7 @@ export class SqValuePath {
return true;
}

serializeToString(): string {
const pathObject = {
root: this.root,
items: this.items.map((item) => item.serialize()),
};
return JSON.stringify(pathObject);
}

static deserialize(str: string): SqValuePath {
const parsed = JSON.parse(str);
const items = parsed.items.map(SqPathItem.deserialize);
return new SqValuePath({ root: parsed.root, items });
}

itemsAsValuePaths({ includeRoot = false }) {
allSqValuePathSubsets({ includeRoot = false }) {
const root = new SqValuePath({
root: this.root,
items: [],
Expand All @@ -153,93 +233,4 @@ export class SqValuePath {
);
return includeRoot ? [root, ...leafs] : leafs;
}

isRoot() {
return this.items.length === 0;
}

static findByOffset({
ast,
offset,
}: {
ast: ASTNode;
offset: number;
}): SqValuePath | undefined {
const findLoop = (ast: ASTNode): SqPathItem[] => {
switch (ast.type) {
case "Program": {
for (const statement of ast.statements) {
if (locationContains(statement.location, offset)) {
return findLoop(statement);
}
}
return [];
}
case "Dict": {
for (const pair of ast.elements) {
if (
!locationContains(
{
source: ast.location.source,
start: pair.location.start,
end: pair.location.end,
},
offset
)
) {
continue;
}

if (
pair.type === "KeyValue" &&
pair.key.type === "String" // only string keys are supported
) {
return [
SqPathItem.fromString(pair.key.value),
...findLoop(pair.value),
];
} else if (pair.type === "Identifier") {
return [SqPathItem.fromString(pair.value)]; // this is a final node, no need to findLoop recursively
}
}
return [];
}
case "Array": {
for (let i = 0; i < ast.elements.length; i++) {
const element = ast.elements[i];
if (locationContains(element.location, offset)) {
return [SqPathItem.fromNumber(i), ...findLoop(element)];
}
}
return [];
}
case "LetStatement": {
return [
SqPathItem.fromString(ast.variable.value),
...findLoop(ast.value),
];
}
case "DefunStatement": {
return [
SqPathItem.fromString(ast.variable.value),
...findLoop(ast.value),
];
}
case "Block": {
if (
ast.statements.length === 1 &&
["Array", "Dict"].includes(ast.statements[0].type)
) {
return findLoop(ast.statements[0]);
}
}
}
return [];
};

return new SqValuePath({
root: "bindings", // not important, will probably be removed soon
items: findLoop(ast),
});
}
}
Loading