cgen: fix pointer reference in for-in fixed-array iteration with & [fj4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT] - #28166
Conversation
… [fj4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 874a934146
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
| if !is_fixed_array { | ||
| addr := if node.val_is_mut { '&' } else { '' } | ||
| addr := if node.val_is_mut || node.val_is_ref { '&' } else { '' } |
There was a problem hiding this comment.
Preserve pointer elements during reference iteration
When the fixed array's element type is already a pointer, such as mut items := [2]&Item{} followed by for item in &items, for_in_val_type deliberately leaves the loop variable as &Item rather than creating &&Item. This unconditional & now emits an initializer equivalent to Item *item = &items[idx], whose right side is Item **, so previously valid reference iteration over fixed arrays of pointers fails C compilation. Only take the element address when reference iteration actually added a pointer level.
Useful? React with 👍 / 👎.
Fix
for i in &fixed_arrayproducing invalid C when the array element is a structDescription
When iterating over a fixed array by reference (
for i in &t.bufwheret.bufis a fixed array of structs), the cgen generatesmain__Item* i = (*tmp)[idx]— assigning a struct value to a pointer type.Root Cause
In
vlib/v/gen/c/for.v, the.array_fixedbranch computes the address prefix as:This only checks
val_is_mut, but notval_is_ref. Whenval_is_refis true (the user wrotefor i in &expr), the loop variable is a pointer type (&Item), but the generated C code assigns the element's value instead of its address.Fix
Change the condition to also check
val_is_ref:Reproduction
Before:
error: initializing 'main__Item *' with an expression of incompatible type 'main__Item'After: compiles correctly.
Closes #28128
[fj4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT]