Skip to content

Conversation

@elijahr
Copy link
Contributor

@elijahr elijahr commented Jan 1, 2026

This PR extends the deferred pragma infrastructure from #25403 to support the align pragma with generic type parameters, as well as a new capability: type-level alignment.

Summary

  1. Type-level align pragma: The align pragma is now valid on type definitions, not just fields and variables
  2. Field-level deferred align: Field alignment can use expressions like alignof(T)
  3. Deferred evaluation: Align expressions are evaluated during generic instantiation

Example

const CacheLine = 64

type
  CacheAligned[T] {.align: (if alignof(T) > CacheLine: alignof(T) else: CacheLine).} = object
    value: T

  Aligned128 {.align: 128.} = object
    data: array[64, byte]

# alignof(int) < CacheLine, so CacheLine (64) is used
var x: CacheAligned[int]
x.value = 42

# alignof(Aligned128) > CacheLine, so alignof(T) (128) is used
var y: CacheAligned[Aligned128]
y.value.data[0] = 1

static:
  doAssert alignof(CacheAligned[int]) == CacheLine
  doAssert alignof(CacheAligned[Aligned128]) == 128

Implementation

Pragma processing (pragmas.nim):

  • wAlign added to typePragmas set (previously only in fieldPragmas/varPragmas)
  • Modified wAlign handler to support both type-level and field-level deferred expressions
  • Power-of-2 validation for alignment values

Instantiation (semtypinst.nim):

  • Added wAlign case to applyDeferredPragma for type-level alignment
  • New applyDeferredFieldPragma: Evaluates field-level deferred pragmas
  • New evaluateDeferredFieldPragmas: Orchestrates field pragma evaluation
  • Integration with replaceTypeVarsN for field processing

Tests

  • tests/pragmas/tdeferred_align.nim - Align pragma at type and field level

Dependencies

Enables the size pragma to accept expressions involving type parameters
for generic imported types. The expression is deferred and evaluated
when the generic type is instantiated.

Example:
  type
    CppAtomic[T] {.importcpp, size: sizeof(T).} = object
Enables the align pragma to accept expressions involving type parameters
for generic types and fields. The expression is deferred and evaluated
when the generic type is instantiated. Also adds support for the align
pragma on types.

Type-level example:
  type
    GenericAligned[T] {.importc, align: alignof(T).} = object

Field-level example:
  type
    Container[T] = object
      data {.align: alignof(T).}: T
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