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

Validate function calls #2

Open
wants to merge 4 commits into
base: validate_pr1
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions packages/compiler/lib/main.tsp
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import "./lib.tsp";
import "./decorators.tsp";
import "./reflection.tsp";
import "./projected-names.tsp";
import "./methods.tsp";
45 changes: 45 additions & 0 deletions packages/compiler/lib/methods.tsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
namespace TypeSpec.ValueMethods;

interface Array<TElementType> {
someOf(cb: Private.BooleanReturnCb<TElementType>): boolean;
allOf(cb: Private.BooleanReturnCb<TElementType>): boolean;
noneOf(cb: Private.BooleanReturnCb<TElementType>): boolean;
find(cb: Private.BooleanReturnCb<TElementType>): TElementType | void;
contains(value: TElementType): boolean;
first(n: numeric): TElementType[];
last(n: numeric): TElementType[];
sum(cb?: Private.NumericReturnCb<TElementType>): numeric;

/**
* Return the minimum value in the array. Optionally pass a callback to select the value to compare.
*/
min(cb?: Private.NumericReturnCb<TElementType>): numeric;

/**
* Return the maximum value in the array. Optionally pass a callback to select the value to compare.
*/
max(cb?: Private.NumericReturnCb<TElementType>): numeric;
distinct(): TElementType[];
length(): numeric;
}

interface String {
contains(value: string): boolean;
startsWith(value: string): boolean;
endsWith(value: string): boolean;
slice(start: numeric, end?: numeric, unit?: StringUnit = StringUnit.utf16CodeUnit): string;
concat(value: string): string;
length(unit?: StringUnit = StringUnit.utf16CodeUnit): numeric;
}

enum StringUnit {
codePoint,
utf16CodeUnit,
utf8CodeUnit,
graphemeCluster,
}

namespace Private {
op BooleanReturnCb<T>(value: T): boolean;
op NumericReturnCb<T>(value: T): numeric;
}
173 changes: 124 additions & 49 deletions packages/compiler/src/core/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
MemberExpressionNode,
MemberNode,
MemberType,
MetaMemberKey,
Model,
ModelExpressionNode,
ModelIndexer,
Expand Down Expand Up @@ -302,8 +303,6 @@ export function createChecker(program: Program): Checker {
const nullType = createType({ kind: "Intrinsic", name: "null" } as const);
const nullSym = createSymbol(undefined, "null", SymbolFlags.None);

const sharedMetaProperties = createSharedMetaProperties();

const projectionsByTypeKind = new Map<Type["kind"], ProjectionStatementNode[]>([
["Model", []],
["ModelProperty", []],
Expand Down Expand Up @@ -351,6 +350,7 @@ export function createChecker(program: Program): Checker {
}
}

const sharedMetaInterfaces: Partial<Record<MetaMemberKey, Sym>> = createSharedMetaInterfaces();
let evalContext: EvalContext | undefined = undefined;

const checker: Checker = {
Expand Down Expand Up @@ -414,6 +414,21 @@ export function createChecker(program: Program): Checker {
getSymbolLinks(nullSym).type = nullType;
}

function createSharedMetaInterfaces(): Partial<Record<MetaMemberKey, Sym>> {
if (!typespecNamespaceBinding) return {};

const interfaces: Partial<Record<MetaMemberKey, Sym>> = {};

const vmns = typespecNamespaceBinding.exports!.get("ValueMethods")!;
for (const [name, sym] of vmns.exports!) {
if (sym.flags & SymbolFlags.Interface) {
interfaces[name as MetaMemberKey] = sym;
}
}

return interfaces;
}

function getStdType<T extends keyof StdTypes>(name: T): StdTypes[T] {
const type = stdTypes[name];
if (type !== undefined) {
Expand Down Expand Up @@ -944,7 +959,6 @@ export function createChecker(program: Program): Checker {
}

if (tooFew) {
throw new Error("TOO FEW");
reportCheckerDiagnostic(
createDiagnostic({
code: "invalid-template-args",
Expand Down Expand Up @@ -1940,9 +1954,9 @@ export function createChecker(program: Program): Checker {
} else {
addCompletions(base.metatypeMembers);
const type = base.type ?? getTypeForNode(base.declarations[0], undefined);
const members = sharedMetaProperties[metaMemberKey(type)];
const members = getTableForMetaMembers(type, undefined);
if (members) {
for (const sym of Object.values(members).map((m: any) => m.symbol)) {
for (const sym of members.values()) {
addCompletion(sym.name, sym);
}
}
Expand Down Expand Up @@ -2290,13 +2304,42 @@ export function createChecker(program: Program): Checker {
? base.type!
: checkTypeReferenceSymbol(base, node, mapper);

const metaMembers = sharedMetaProperties[metaMemberKey(baseType)];
if (!metaMembers) return undefined;
const metaProp = metaMembers[node.id.sv];
return metaProp.symbol;
const table = getTableForMetaMembers(baseType, mapper);
if (!table) return undefined;

return table.get(node.id.sv);
}

function getTableForMetaMembers(baseType: Type, mapper: TypeMapper | undefined) {
const key = metaMemberKey(baseType);
const ifaceSym = sharedMetaInterfaces[key];
if (!ifaceSym) {
return undefined;
}

if (key === "Array") {
// Array needs instantiated.
const ifaceNode = ifaceSym.declarations[0] as InterfaceStatementNode;
const param: TemplateParameter = getTypeForNode(ifaceNode.templateParameters[0]) as any;
const ifaceType = getOrInstantiateTemplate(
ifaceNode,
[param],
[(baseType as Model).indexer!.value],
mapper
) as Interface;
lateBindMemberContainer(ifaceType);
lateBindMembers(ifaceType, ifaceType.symbol!);
return getOrCreateAugmentedSymbolTable(ifaceType.symbol!.members!);
} else {
const links = getSymbolLinks(ifaceSym);
const ifaceType = links.declaredType as Interface; // should be checked by now.
lateBindMemberContainer(ifaceType);
lateBindMembers(ifaceType, ifaceType.symbol!);
return getOrCreateAugmentedSymbolTable(ifaceType.symbol!.members!);
}
}

function metaMemberKey(baseType: Type) {
function metaMemberKey(baseType: Type): MetaMemberKey {
return baseType.kind === "Model" && isArrayModelType(program, baseType)
? ("Array" as const)
: baseType.kind === "Scalar" && isRelatedToScalar(baseType, getStdType("string"))
Expand Down Expand Up @@ -3471,12 +3514,76 @@ export function createChecker(program: Program): Checker {
case SyntaxKind.ProjectionCallExpression: {
const target = checkLogicExpression(node.target, mapper);
if (!target) return;

if (target.type.kind !== "Operation") {
reportCheckerDiagnostic(
createDiagnostic({
code: "type-expected",
format: {
actual: target.type.kind,
expected: "Operation",
},
target: node,
})
);
return;
}
const expectedArgTypes = [...target.type.parameters.properties.values()];

const minArgs = expectedArgTypes.filter((x) => !x.optional).length;
const maxArgs = expectedArgTypes.length;

if (node.arguments.length < minArgs) {
reportCheckerDiagnostic(
createDiagnostic({
code: "invalid-function-args",
messageId: "tooFew",
format: {
actual: String(node.arguments.length),
expected: String(minArgs),
},
target: node,
})
);
return;
} else if (node.arguments.length > maxArgs) {
reportCheckerDiagnostic(
createDiagnostic({
code: "invalid-function-args",
messageId: "tooMany",
format: {
actual: String(node.arguments.length),
expected: String(maxArgs),
},
target: node,
})
);
return;
}

const args = [];
for (const arg of node.arguments) {
const argResult = checkLogicExpression(arg, mapper);
if (!argResult) return;
args.push(argResult);
for (let i = 0; i < node.arguments.length; i++) {
const expectedType = expectedArgTypes[i];
const argType = checkLogicExpression(node.arguments[i], mapper);
if (!argType) return;
if (!isTypeAssignableTo(argType.type, expectedType.type, argType.type)[0]) {
reportCheckerDiagnostic(
createDiagnostic({
code: "invalid-function-args",
messageId: "incorrect",
format: {
name: expectedType.name,
actual: getTypeName(argType.type),
expected: getTypeName(expectedType.type),
},
target: node,
})
);
return;
}
args.push(argType);
}

return {
logic: {
kind: "CallExpression",
Expand Down Expand Up @@ -5569,6 +5676,9 @@ export function createChecker(program: Program): Checker {
return isAssignableToUnion(source, target, diagnosticTarget);
} else if (target.kind === "Enum") {
return isAssignableToEnum(source, target, diagnosticTarget);
} else if (target.kind === "Operation" && source.kind === "Operation") {
// todo: check if the operation is assignable
return [true, []];
}

return [false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
Expand Down Expand Up @@ -5885,41 +5995,6 @@ export function createChecker(program: Program): Checker {
if (type.kind === "Model") return stdType === undefined || stdType === type.name;
return false;
}

function createSharedMetaProperties(): Partial<Record<Type["kind"] | "Array" | "String", any>> {
function createSharedMetaProperty(scope: string, name: string) {
const type = createAndFinishType({ kind: "Intrinsic", name: scope + "::" + name });
const symbol = createSymbol(undefined, name, SymbolFlags.LateBound);
mutate(symbol).type = type as any; // intrinsics have a set name, need to fix this
return {
type,
symbol,
};
}

return {
Array: {
someOf: createSharedMetaProperty("Array", "someOf"),
allOf: createSharedMetaProperty("Array", "allOf"),
noneOf: createSharedMetaProperty("Array", "noneOf"),
find: createSharedMetaProperty("Array", "find"),
contains: createSharedMetaProperty("Array", "contains"),
first: createSharedMetaProperty("Array", "first"),
last: createSharedMetaProperty("Array", "last"),
sum: createSharedMetaProperty("Array", "sum"),
min: createSharedMetaProperty("Array", "min"),
max: createSharedMetaProperty("Array", "max"),
distinct: createSharedMetaProperty("Array", "distinct"),
},
String: {
startsWith: createSharedMetaProperty("String", "startsWith"),
endsWith: createSharedMetaProperty("String", "endsWith"),
contains: createSharedMetaProperty("String", "contains"),
slice: createSharedMetaProperty("String", "slice"),
concat: createSharedMetaProperty("String", "concat"),
},
};
}
}

function isAnonymous(type: Type) {
Expand Down
5 changes: 5 additions & 0 deletions packages/compiler/src/core/helpers/operation-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export function listOperationsIn(
): Operation[] {
const operations: Operation[] = [];

const globalNamespace = container.kind === "Namespace" && container.name === "";

function addOperations(current: Namespace | Interface) {
if (current.kind === "Interface" && isTemplateDeclaration(current)) {
// Skip template interface operations
Expand All @@ -42,6 +44,9 @@ export function listOperationsIn(
];

for (const child of children) {
if (globalNamespace && child.name === "TypeSpec" && child.namespace === container) {
continue;
}
addOperations(child);
}
}
Expand Down
5 changes: 5 additions & 0 deletions packages/compiler/src/core/helpers/usage-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,12 @@ function trackUsage(
}

function addUsagesInNamespace(namespace: Namespace, usages: Map<TrackableType, UsageFlags>): void {
const globalNamespace = namespace.name === "";

for (const subNamespace of namespace.namespaces.values()) {
if (globalNamespace && subNamespace.name === "TypeSpec") {
continue;
}
addUsagesInNamespace(subNamespace, usages);
}
for (const Interface of namespace.interfaces.values()) {
Expand Down
13 changes: 13 additions & 0 deletions packages/compiler/src/core/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,10 @@ const diagnostics = {
default: paramMessage`Shadowing parent template parmaeter with the same name "${"name"}"`,
},
},

/**
* Validation clause
*/
"type-expected": {
severity: "error",
messages: {
Expand All @@ -494,6 +498,15 @@ const diagnostics = {
},
},

"invalid-function-args": {
severity: "error",
messages: {
default: paramMessage`Invalid arguments for function "${"name"}".`,
tooFew: paramMessage`Too few arguments. Expected at least ${"expected"} argument(s) but got ${"actual"}.`,
tooMany: paramMessage`Too many arguments. Expected at most ${"expected"} argument(s) but got ${"actual"}.`,
incorrect: paramMessage`Argument '${"name"}' has incorrect type. Expected ${"expected"} but got ${"actual"}.`,
},
},
/**
* Configuration
*/
Expand Down
2 changes: 2 additions & 0 deletions packages/compiler/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ export type IntrinsicScalarName =
| "boolean"
| "url";

export type MetaMemberKey = Type["kind"] | "Array" | "String";

export type NeverIndexer = { key: NeverType; value: undefined };
export type ModelIndexer = {
key: Scalar;
Expand Down
Loading