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

[typespec-vscode] Make 'convert to object value' code fix recursive #5342

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineCodeFix, getSourceLocation } from "../diagnostics.js";
import type { ModelExpressionNode } from "../types.js";
import { SyntaxKind, type CodeFixEdit, type ModelExpressionNode } from "../types.js";

/**
* Quick fix that convert a model expression to an object value.
Expand All @@ -9,8 +9,26 @@ export function createModelToObjectValueCodeFix(node: ModelExpressionNode) {
id: "model-to-object-value",
label: `Convert to an object value \`#{}\``,
fix: (context) => {
const result: CodeFixEdit[] = [];

const location = getSourceLocation(node);
return context.prependText(location, "#");
result.push(context.prependText(location, "#"));
createChildModelToObjValCodeFix(node);

return result;

function createChildModelToObjValCodeFix(node: ModelExpressionNode) {
for (const prop of node.properties.values()) {
if ("value" in prop) {
mzhongl524 marked this conversation as resolved.
Show resolved Hide resolved
const childNode = prop.value;
if (childNode.pos > node.pos && childNode.kind === SyntaxKind.ModelExpression) {
mzhongl524 marked this conversation as resolved.
Show resolved Hide resolved
const locationChild = getSourceLocation(childNode);
result.push(context.prependText(locationChild, "#"));
createChildModelToObjValCodeFix(childNode);
}
}
}
}
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,21 @@ it("it change model expression to an object value", async () => {
}
`);
});

it("it recursively changes the model expression to the corresponding object value", async () => {
await expectCodeFixOnAst(
`
@example(┆{Bar : {Baz : "Hello"}})
mzhongl524 marked this conversation as resolved.
Show resolved Hide resolved
model Foo { Bar : Bar; }
model Bar { Baz : string }
`,
(node) => {
strictEqual(node.kind, SyntaxKind.ModelExpression);
return createModelToObjectValueCodeFix(node);
},
).toChangeTo(`
@example(#{Bar : #{Baz : "Hello"}})
model Foo { Bar : Bar; }
model Bar { Baz : string }
`);
});
Loading