Skip to content
Closed
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
33 changes: 33 additions & 0 deletions src/semantic/type-assertion-checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,46 @@ class TypeAssertionChecker {
}
}

private checkOpaqueSource(ta: TypeAssertionNode, fields: InterfaceField[]): void {
const inner = ta.expression as { type: string };
if (inner.type !== "type_assertion") return;
const innerTa = ta.expression as TypeAssertionNode;
const src = innerTa.assertedType;
if (src !== "unknown" && src !== "any" && src !== "object") return;

const fieldNames: string[] = [];
for (let i = 0; i < fields.length; i++) {
fieldNames.push(this.stripOpt((fields[i] as InterfaceField).name));
}

const output = formatCompileError(
this.sourceCode,
"inline type assertion 'as { " +
fieldNames.join("; ") +
" }' on opaque source (via 'as " +
src +
"') produces wrong GEP indices at runtime",
ta.loc,
"use 'as NamedInterface' instead of inline '{ ... }' when casting from '" + src + "'",
[
"inline assertion field positions become GEP indices in native code",
"opaque sources have no source interface for the prefix checker to verify against",
"declare a named interface with the correct field layout and cast to that",
],
);
process.stderr.write(output);
process.exit(1);
}

private validateInlineAssertion(ta: TypeAssertionNode): void {
const assertedType = ta.assertedType;
if (!assertedType.startsWith("{")) return;

const parsedFields = this.parseInlineFields(assertedType);
if (parsedFields.length < 2) return;

this.checkOpaqueSource(ta, parsedFields);

const assertedNames: string[] = [];
for (let i = 0; i < parsedFields.length; i++) {
const pf = parsedFields[i] as InterfaceField;
Expand Down
11 changes: 11 additions & 0 deletions tests/fixtures/errors/opaque-inline-cast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// @test-compile-error: inline type assertion
interface Node {
type: string;
value: number;
name: string;
}
function process(x: Node): number {
const y = x as unknown as { type: string; value: number };
return y.value;
}
console.log(process({ type: "a", value: 42, name: "test" }));
Loading