|
27 | 27 | // an example of a correct date string. |
28 | 28 | --- |
29 | 29 |
|
| 30 | +# [For Christmas: Self-Referential Global Values]($section.id('2024-12-25')) |
| 31 | + |
| 32 | +Author: Matthew Lugg |
| 33 | + |
| 34 | +I recently took it upon myself to tackle [issue #131](https://github.com/ziglang/zig/issues/131). This |
| 35 | +has been a long-standing bug in the compiler, dating way back to the earliest days of the C++ bootstrap |
| 36 | +compiler: it was the 9th oldest open issue in the Zig respository! Essentially, fixing it allows you to |
| 37 | +write code like this: |
| 38 | + |
| 39 | +```zig |
| 40 | +const S = struct { ptr: *const S, x: u32 }; |
| 41 | + |
| 42 | +// `foo` contains a pointer to itself |
| 43 | +const foo: S = .{ .ptr = &foo, .x = 123 }; |
| 44 | + |
| 45 | +// Or: |
| 46 | + |
| 47 | +// `a` contains a pointer to `b`, and... |
| 48 | +// `b` contains a pointer to `a` |
| 49 | +const a: S = .{ .ptr = &b, .x = 123 }; |
| 50 | +const b: S = .{ .ptr = &a, .x = 456 }; |
| 51 | +``` |
| 52 | + |
| 53 | +Previously, both of the examples above would have failed with a "dependency loop detected" error; now, |
| 54 | +they compile just as you expect (and the same works if they're declared `var`, of course). |
| 55 | + |
| 56 | +This issue had been open for so long because it actually requires a non-trivial extension to the compiler: |
| 57 | +separating semantic analysis for the *type* and *value* of container-level declarations. This is complicated |
| 58 | +further by the fact that some global declarations might not have a type annotation, and that some (such as |
| 59 | +`extern` declarations) have a *type* but no *value*. It also interacts with the work-in-progress incremental |
| 60 | +compilation feature in non-trivial ways, so we had to make sure we got that right. All in all, this resulted |
| 61 | +in a [pretty bulky diff](https://github.com/ziglang/zig/pull/22303) to the compiler. |
| 62 | + |
| 63 | +Regardless, the point is, this now works on Zig `master`! If you have a use case for it, feel free to give it |
| 64 | +a try -- and please do open an issue if you encounter any problems along the way. |
| 65 | + |
| 66 | +Merry Christmas to those who celebrate! |
| 67 | + |
30 | 68 | # [Zig Bootstrap Porting Progress]($section.id('2024-11-19')) |
31 | 69 |
|
32 | 70 | Author: Alex Rønne Petersen |
|
0 commit comments