Skip to content

Cast a constant array literal to another element type element by element - #330

Open
ASDAlexander77 wants to merge 1 commit into
mainfrom
union-array-literal-cast
Open

ASDAlexander77 wants to merge 1 commit into
mainfrom
union-array-literal-cast

Conversation

@ASDAlexander77

Copy link
Copy Markdown
Owner

Problem

A constant array keeps the element type its literal was built with. const c = [1, 2] is a const_array<si32>, and so is [1, 2] given to a union such as number[] | string, where no single array type guides the literal. Casting it to number[] produced a bare ts.Cast, and lowering turns a const array into an array by copying its data as it is, so number elements were read out of s32 data:

const c = [1, 2, 3]; let u: number[] = c;   // garbage values
let v: number[] | string = [1, 2];          // garbage length (reads a pointer)

The compiler printed only a warning ("invalid cast", or "source array and destination array have different types" followed by one) and exited 0, for a local initializer, an assignment and a function argument alike. Literals that do have a single target type (let u: number[] = [1, 2], f([1, 2]) with f(u: number[]), <number[]>[1, 2]) were already fine: their elements are cast while the literal is built.

Fix

New castConstArrayToArray in cast(): a constant array cast to an array of another element type is built with CreateArray from its elements, each cast to the target element type (and retained for the data block, as array literals do). Arrays whose element type already matches keep the existing copy.

Not changed:

  • Nested literals (let u: number[][] | string = [[1, 2]]) still fail module verification. That is a loud error, not a miscompile.
  • Lowering's "invalid cast" warning with an undef result in CastLogicHelper.h is left as it is; its TODO says conditional compiling relies on it.

Tests

New 00const_array_to_array_elements.ts (compile, JIT and corpus variants): a const variable to number[], and a union initializer, assignment and parameter, checking length, elements and fractional arithmetic on the converted elements.

Full Windows debug suite (ctest -R "^test-"): 2757/2757 passed.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant