Skip to content

Allow passing values parameters #7137

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

Merged
merged 8 commits into from
May 7, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
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"
---

Allow passing template parameters as property defaults
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: fix
packages:
- "@typespec/compiler"
---

Allow passing tempalate parameter values in object and array values used inside the template
50 changes: 33 additions & 17 deletions packages/compiler/src/core/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ import {
UnknownType,
UsingStatementNode,
Value,
ValueWithTemplate,
VoidType,
} from "./types.js";

Expand Down Expand Up @@ -303,7 +304,7 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
TypeReferenceNode | MemberExpressionNode | IdentifierNode,
Sym | undefined
>();
const valueExactTypes = new WeakMap<Value, Type>();
const valueExactTypes = new WeakMap<ValueWithTemplate, Type>();
let onCheckerDiagnostic: (diagnostic: Diagnostic) => void = (x: Diagnostic) => {
program.reportDiagnostic(x);
};
Expand Down Expand Up @@ -548,7 +549,6 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
node: Node,
mapper?: TypeMapper,
constraint?: CheckValueConstraint,
options: { legacyTupleAndModelCast?: boolean } = {},
): Value | null {
const initial = checkNode(node, mapper, constraint);
if (initial === null) {
Expand All @@ -560,15 +560,28 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
} else {
entity = initial;
}
// if (options.legacyTupleAndModelCast && entity !== null && isType(entity)) {
// entity = legacy_tryTypeToValueCast(entity, constraint, node);
// }
if (entity === null) {
return null;
}
if (isValue(entity)) {
return constraint ? inferScalarsFromConstraints(entity, constraint.type) : entity;
}
// If a template parameter that can be a value is used in a template declaration then we allow it but we return null because we don't have an actual value.
if (
entity.kind === "TemplateParameter" &&
entity.constraint?.valueType &&
entity.constraint.type === undefined &&
mapper === undefined
) {
return createValue(
{
entityKind: "Value",
valueKind: "TemplateValue",
type: entity.constraint.valueType,
},
entity.constraint.valueType,
) as any;
}
reportExpectedValue(node, entity);
return null;
}
Expand Down Expand Up @@ -3810,7 +3823,7 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
);
}

function createValue<T extends Value>(value: T, preciseType: Type): T {
function createValue<T extends ValueWithTemplate>(value: T, preciseType: Type): T {
valueExactTypes.set(value, preciseType);
return value;
}
Expand Down Expand Up @@ -4622,7 +4635,7 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
pendingResolutions.start(sym, ResolutionKind.Type);
type.type = getTypeForNode(prop.value, mapper);
if (prop.default) {
const defaultValue = checkDefaultValue(prop.default, type.type);
const defaultValue = checkDefaultValue(prop.default, type.type, mapper);
if (defaultValue !== null) {
type.defaultValue = defaultValue;
}
Expand Down Expand Up @@ -4659,27 +4672,30 @@ export function createChecker(program: Program, resolver: NameResolver): Checker
};
}

function checkDefaultValue(defaultNode: Node, type: Type): Value | null {
function checkDefaultValue(
defaultNode: Node,
type: Type,
mapper: TypeMapper | undefined,
): Value | null {
if (isErrorType(type)) {
// if the prop type is an error we don't need to validate again.
return null;
}
const defaultValue = getValueForNode(
defaultNode,
undefined,
{
kind: "assignment",
type,
},
{ legacyTupleAndModelCast: true },
);
const defaultValue = getValueForNode(defaultNode, mapper, {
kind: "assignment",
type,
});
if (defaultValue === null) {
return null;
}
const [related, diagnostics] = relation.isValueOfType(defaultValue, type, defaultNode);
if (!related) {
reportCheckerDiagnostics(diagnostics);
return null;
} else if ((defaultValue.valueKind as any) === "TemplateValue") {
// Right now we don't want to expose `TemplateValue` in the type graph.
// And as interating with the template declaration is not a supported feature we can just drop it.
return null;
} else {
return { ...defaultValue, type };
}
Expand Down
12 changes: 12 additions & 0 deletions packages/compiler/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,9 @@ export type Value =
| EnumValue
| NullValue;

/** @internal */
export type ValueWithTemplate = Value | TemplateValue;

interface BaseValue {
readonly entityKind: "Value";
readonly valueKind: string;
Expand Down Expand Up @@ -380,6 +383,15 @@ export interface NullValue extends BaseValue {
value: null;
}

/**
* This is an internal type that represent a value while in a template declaration.
* This type should currently never be exposed on the type graph(unlike TemplateParameter).
* @internal
*/
export interface TemplateValue extends BaseValue {
valueKind: "TemplateValue";
}

//#endregion Values

export interface Scalar extends BaseType, DecoratedType, TemplatedTypeBase {
Expand Down
28 changes: 28 additions & 0 deletions packages/compiler/test/checker/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,34 @@ describe("compiler: models", () => {
deepStrictEqual(foo.defaultValue?.value, "up-value");
});
});

describe("using a template parameter", () => {
it(`set it with valid constraint`, async () => {
testHost.addTypeSpecFile(
"main.tsp",
`
model A<T extends valueof string> { @test foo?: string = T }
alias Test = A<"Abc">;
`,
);
const { foo } = (await testHost.compile("main.tsp")) as { foo: ModelProperty };
strictEqual(foo.defaultValue?.valueKind, "StringValue");
});

it(`error if constraint is not compatible with property type`, async () => {
testHost.addTypeSpecFile(
"main.tsp",
`
model A<T extends valueof int32> { @test foo?: string = T }
`,
);
const diagnostics = await testHost.diagnose("main.tsp");
expectDiagnostics(diagnostics, {
code: "unassignable",
message: "Type 'int32' is not assignable to type 'string'",
});
});
});
});

describe("doesn't allow a default of different type than the property type", () => {
Expand Down
57 changes: 57 additions & 0 deletions packages/compiler/test/checker/templates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -982,4 +982,61 @@ describe("compiler: templates", () => {
strictEqual(members[1][1].name, "string");
});
});

describe("template declaration passing values", () => {
it("allows passing to a decorator expecting that value", async () => {
testHost.addJsFile("effect.js", {
$call: () => null,
});

testHost.addTypeSpecFile(
"main.tsp",
`
import "./effect.js";
extern dec call(target, arg: valueof string);
@call(T) model Dec<T extends valueof string> {}
`,
);
const diagnostics = await testHost.diagnose("main.tsp");
expectDiagnosticEmpty(diagnostics);
});

it("allows passing to a decorator expecting a composed value", async () => {
testHost.addJsFile("effect.js", {
$call: () => null,
});

testHost.addTypeSpecFile(
"main.tsp",
`
import "./effect.js";
extern dec call(target, arg: valueof unknown);
@call(#{foo: T}) model Dec<T extends valueof string> {}
`,
);
const diagnostics = await testHost.diagnose("main.tsp");
expectDiagnosticEmpty(diagnostics);
});

it("validate incompatible composed values", async () => {
testHost.addJsFile("effect.js", {
$call: () => null,
});

testHost.addTypeSpecFile(
"main.tsp",
`
import "./effect.js";
extern dec call(target, arg: valueof {foo: int32});
@call(#{foo: T}) model Dec<T extends valueof string> {}
`,
);
const diagnostics = await testHost.diagnose("main.tsp");
expectDiagnostics(diagnostics, {
code: "invalid-argument",
message:
"Argument of type '{ foo: string }' is not assignable to parameter of type '{ foo: int32 }'",
});
});
});
});
Loading