Skip to content

Commit

Permalink
Report error diagnostic when trying to flattening a model with polymo…
Browse files Browse the repository at this point in the history
…rphsim (#1223)

resolve #959

---------

Co-authored-by: Timothee Guerin <[email protected]>
Co-authored-by: Mingzhe Huang (from Dev Box) <[email protected]>
  • Loading branch information
3 people committed Jul 25, 2024
1 parent 01e5e0d commit 74b3302
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: feature
packages:
- "@azure-tools/typespec-client-generator-core"
---

Report error diagnostic when trying to flattening a model with polymorphism
8 changes: 8 additions & 0 deletions packages/typespec-client-generator-core/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
Type,
Union,
createDiagnosticCollector,
getDiscriminator,
getNamespaceFullName,
getProjectedName,
ignoreDiagnostics,
Expand Down Expand Up @@ -958,6 +959,13 @@ export function $flattenProperty(
target: ModelProperty,
scope?: LanguageScopes
) {
if (getDiscriminator(context.program, target.type)) {
reportDiagnostic(context.program, {
code: "flatten-polymorphism",
format: {},
target: target,
});
}
setScopedDecoratorData(context, $flattenProperty, flattenPropertyKey, target, true, scope); // eslint-disable-line deprecation/deprecation
}

Expand Down
6 changes: 6 additions & 0 deletions packages/typespec-client-generator-core/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@ export const $lib = createTypeSpecLibrary({
default: paramMessage`Value in example file '${"relativePath"}' does not follow its definition:\n${"value"}`,
},
},
"flatten-polymorphism": {
severity: "error",
messages: {
default: `Cannot flatten property of polymorphic type.`,
},
},
},
});

Expand Down
24 changes: 24 additions & 0 deletions packages/typespec-client-generator-core/test/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2566,6 +2566,30 @@ describe("typespec-client-generator-core: decorators", () => {
code: "decorator-wrong-target",
});
});

it("throws error when used on a polymorphism type", async () => {
const diagnostics = await runner.diagnose(`
@service
@test namespace MyService {
#suppress "deprecated" "@flattenProperty decorator is not recommended to use."
@test
model Model1{
@flattenProperty
child: Model2;
}
@test
@discriminator("kind")
model Model2{
kind: string;
}
}
`);

expectDiagnostics(diagnostics, {
code: "@azure-tools/typespec-client-generator-core/flatten-polymorphism",
});
});
});

describe("@clientName", () => {
Expand Down

0 comments on commit 74b3302

Please sign in to comment.