twinbasic / lang-design

Language Design for twinBASIC
MIT License
11 stars 1 forks source link

Redim LongPtr Array (Long vs. LongLong) #47

Open Kr00l opened 2 years ago

Kr00l commented 2 years ago

Just wanted to point this out. If it is not relevant or a non-issue please mark as resolved.

in tB we can do following:

Dim MyArrPtr() As LongPtr
ReDim MyArrPtr(0 To 10) As LongPtr

However, VBA7 will convert the ReDim ... As LongPtr into As Long or As LongLong (depending if office 32bit or 64bit is used)

I am wondering if this is a bug in VBA7 or a feature... and if that has any other implication for porting a code done in 32bit to a 64bit environment.

Greedquest commented 2 years ago

As in the VBE rewrites LongPtr to LongLong for you only in Redim statements? Yeah that doesn't seem like a useful or relied upon feature, I say scrap it as it ofc makes the code less portable between 32 and 64 bit compilation targets (the code would stop working on 32-bit).

Also, until we have TypeDef/ type aliasing support (where I can declare Public TypeAlias HWND As LongLong: Dim a As HWND), LongLong and LongPtr have different connotations IMO. So even if I'm exclusively targeting 64 bit, I would still use both LongPtr and LongLong depending on context; I don't want my LongPtr to be eagerly resolved to LongLong if my code is talking about pointers and memory addresses, the alias is more readable.

Greedquest commented 2 years ago

To expand on that, the VBA language spec stipulates that:

An implementation-defined LongPtr type alias is also defined, mapping to the underlying declared type the implementation will use to hold pointer or handle values. 32-bit implementations SHOULD map LongPtr to Long, and 64-bit implementations SHOULD map LongPtr to LongLong, although implementations MAY map LongPtr to an implementation-defined pointer type. The LongPtr type alias is valid anywhere its underlying declared type is valid.

(see this answer on SO https://stackoverflow.com/a/61032167/6609896)

So LongPtr semantically refers not to LongLong or Long, but rather an implementation-defined pointer type, so we must not assume LongLong and LongPtr are interchangeable in a 64 bit environment. Depending on the platform, tB is entitled within the rules of the language spec to use 32 bit pointers even in a 64 bit operating system - and VBA7 autocorrect behavior would then just be buggy.

Kr00l commented 2 years ago

Yes.

My workaround is to omit the As LongPtr in the ReDim line.

Dim MyArrPtr() As LongPtr
ReDim MyArrPtr(0 To 10)
Kr00l commented 2 years ago

IMO in tB it is correct that ReDim .. As LongPtr is allowed. However, I think a compiler warning/information may be good to engage the user maybe to skip the As LongPtr to hint at this problem for VBA7.

This way we avoid new code snippets done in tB which would be troubling when porting to VBA7.