diff --git a/.chronus/changes/fix-alias-expr-2024-7-12-19-19-19.md b/.chronus/changes/fix-alias-expr-2024-7-12-19-19-19.md new file mode 100644 index 0000000000..e6a69e3753 --- /dev/null +++ b/.chronus/changes/fix-alias-expr-2024-7-12-19-19-19.md @@ -0,0 +1,8 @@ +--- +# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking +changeKind: fix +packages: + - "@typespec/compiler" +--- + +Fix model expression defined in alias will resolve its namespace from the namespace where the alias was declared diff --git a/packages/compiler/src/core/checker.ts b/packages/compiler/src/core/checker.ts index 82487c8996..c7ccc5927a 100644 --- a/packages/compiler/src/core/checker.ts +++ b/packages/compiler/src/core/checker.ts @@ -2409,6 +2409,7 @@ export function createChecker(program: Program): Checker { function getParentNamespaceType( node: + | AliasStatementNode | ModelStatementNode | ScalarStatementNode | NamespaceStatementNode @@ -2432,6 +2433,7 @@ export function createChecker(program: Program): Checker { let parent: Node | undefined = node.parent; while (parent !== undefined) { if ( + parent.kind === SyntaxKind.AliasStatement || parent.kind === SyntaxKind.ModelStatement || parent.kind === SyntaxKind.ScalarStatement || parent.kind === SyntaxKind.OperationStatement || diff --git a/packages/compiler/test/checker/alias.test.ts b/packages/compiler/test/checker/alias.test.ts index 3cc2201ed8..283ae29e30 100644 --- a/packages/compiler/test/checker/alias.test.ts +++ b/packages/compiler/test/checker/alias.test.ts @@ -1,6 +1,6 @@ import { ok, strictEqual } from "assert"; import { beforeEach, describe, it } from "vitest"; -import { Model, Type, Union } from "../../src/core/types.js"; +import { Model, Namespace, Type, Union } from "../../src/core/types.js"; import { TestHost, createTestHost, @@ -194,6 +194,28 @@ describe("compiler: aliases", () => { strictEqual(Baz.properties.get("x")!.type, Bar); }); + it("model expression defined in alias use containing namespace", async () => { + testHost.addTypeSpecFile( + "main.tsp", + ` + @test namespace Foo { + alias B = {a: string}; + } + @test model Test { + prop: Foo.B; + } + ` + ); + + const { Test, Foo } = (await testHost.compile("./")) as { + Foo: Namespace; + Test: Model; + }; + + const expr = Test.properties.get("prop")!.type as Model; + strictEqual(expr.namespace, Foo); + }); + it("emit diagnostics if assign itself", async () => { testHost.addTypeSpecFile( "main.tsp",