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

isErrorModel check for base models #2968

Merged
merged 9 commits into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
8 changes: 8 additions & 0 deletions .chronus/changes/is-error-model-2024-1-29-0-44-17.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: feature
packages:
- "@typespec/compiler"
---

Any subtype of an error(marked with `@error`) is now an error.
18 changes: 15 additions & 3 deletions packages/compiler/src/lib/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,16 +350,28 @@ const errorKey = createStateSymbol("error");

/**
* `@error` decorator marks a model as an error type.
*
* `@error` can only be specified on a model.
* Any derived models (using extends) will also be seen as error types.
*/
export function $error(context: DecoratorContext, entity: Model) {
validateDecoratorUniqueOnNode(context, entity, $error);
context.program.stateSet(errorKey).add(entity);
}

/**
* Check if the type is an error model or a descendant of an error model.
*/
export function isErrorModel(program: Program, target: Type): boolean {
return program.stateSet(errorKey).has(target);
if (target.kind !== "Model") {
return false;
}
let current: Model | undefined = target;
while (current) {
if (program.stateSet(errorKey).has(current)) {
return true;
}
current = target.baseModel;
}
return false;
}

// -- @format decorator ---------------------
Expand Down
8 changes: 8 additions & 0 deletions packages/compiler/test/decorators/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,14 @@ describe("compiler: built-in decorators", () => {
ok(isErrorModel(runner.program, A), "isError should be true");
});

it("applies @error on derived models", async () => {
const { B } = await runner.compile(`
@error model A { }
@test model B extends A { }
`);
ok(isErrorModel(runner.program, B), "isError should be true");
});

it("emit diagnostic if error is not applied to a model", async () => {
const diagnostics = await runner.diagnose(`
@error
Expand Down
Loading