implement sizeof and alignof operator (manually squashed #5664) (#9356)

This commit is contained in:
Timothee Cour 2018-10-13 15:52:28 -07:00 • committed by Andreas Rumpf
commit 745f1642d6
18 changed files with 906 additions and 236 deletions

View file

@ -682,13 +682,30 @@ proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.}
## that one never needs to know ``x``'s size. As a special semantic rule,
## ``x`` may also be a type identifier (``sizeof(int)`` is valid).
##
## Limitations: If used within nim VM context ``sizeof`` will only work
## for simple types.
## Limitations: If used for types that are imported from C or C++,
## sizeof should fallback to the ``sizeof`` in the C compiler. The
## result isn't available for the Nim compiler and therefore can't
## be used inside of macros.
##
## .. code-block:: nim
## sizeof('A') #=> 1
## sizeof(2) #=> 8
when defined(nimHasalignOf):
proc alignof*[T](x: T): int {.magic: "AlignOf", noSideEffect.}
proc alignof*(x: typedesc): int {.magic: "AlignOf", noSideEffect.}
proc offsetOfDotExpr(typeAccess: typed): int {.magic: "OffsetOf", noSideEffect, compileTime.}
template offsetOf*[T](t: typedesc[T]; member: untyped): int =
var tmp: T
offsetOfDotExpr(tmp.member)
template offsetOf*[T](value: T; member: untyped): int =
offsetOfDotExpr(value.member)
#proc offsetOf*(memberaccess: typed): int {.magic: "OffsetOf", noSideEffect.}
when defined(nimtypedescfixed):
proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}