Skip to content

Support sizeof and alignof inside macros for stable types#15497

Merged
straight-shoota merged 3 commits intocrystal-lang:masterfrom
HertzDevil:feature/macro-sizeof-alignof
Mar 19, 2025
Merged

Support sizeof and alignof inside macros for stable types#15497
straight-shoota merged 3 commits intocrystal-lang:masterfrom
HertzDevil:feature/macro-sizeof-alignof

Conversation

@HertzDevil
Copy link
Contributor

This PR enables the use of sizeof and alignof in macro expressions when the type's size and alignment are known to be stable, i.e. their values cannot be changed by adding new code. The idea was raised in this forum thread and possibly in other GitHub issues as well. With this PR you can write compile-time checks like:

{% unless sizeof(Void*) == sizeof(LibC::SizeT) %}
  {% raise "we don't allow the x86 Real Mode here" %}
{% end %}

All types are stable, except for the following:

  • Non-primitive structs, e.g. Bytes
  • ReferenceStorage instances
  • Modules, e.g. GC (not to be confused with GC.class, all metaclasses are stable)
  • Uninstantiated generic types, e.g. Array
  • Annotations, e.g. x = uninitialized Flags (these "types" are ill-behaved anyway)
  • StaticArray, Tuple, NamedTuple, and Union instances containing any unstable constituent types

typeof is disallowed, because we obviously cannot do any kind of non-macro semantic analysis inside macros.

Although the non-macro sizeof and alignof support constants, their macro counterparts do not, even when constant evaluates to a simple compile-time literal (A = 1; {{ sizeof(A) }}).

@HertzDevil HertzDevil marked this pull request as ready for review March 17, 2025 16:41
@straight-shoota straight-shoota added this to the 1.16.0 milestone Mar 17, 2025
@straight-shoota straight-shoota merged commit 0596532 into crystal-lang:master Mar 19, 2025
31 of 32 checks passed
@HertzDevil HertzDevil deleted the feature/macro-sizeof-alignof branch March 19, 2025 17:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants