Skip to content

Commit

Permalink
fixes #18896; fixes #20886; importc types alias doesn't work with dis…
Browse files Browse the repository at this point in the history
…tinct (#24313)

fixes #18896
fixes #20886

```nim
type
  PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer
    # import C's FILE* type; Nim will treat it as a new pointer type
```
This is an excerpt from the Nim manual. In the old Nim versions, it
produces a void pointer type instead of the `FILE*` type that should
have been generated. Because these C types tend to be opaque and adapt
to changes on different platforms. It might affect the portability of
Nim on various OS, i.e. `csource_v2` cannot build on the apline platform
because of `Time` relies on Nim types instead of the `time_t` type.

ref #18851
  • Loading branch information
ringabout authored Oct 16, 2024
1 parent 4a056b1 commit 8be82c3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 8 additions & 2 deletions compiler/ccgtypes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,12 @@ proc getSimpleTypeDesc(m: BModule; typ: PType): Rope =
of tyNil: result = typeNameOrLiteral(m, typ, "void*")
of tyInt..tyUInt64:
result = typeNameOrLiteral(m, typ, NumericalTypeToStr[typ.kind])
of tyDistinct, tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ.skipModifier)
of tyRange, tyOrdinal: result = getSimpleTypeDesc(m, typ.skipModifier)
of tyDistinct:
result = getSimpleTypeDesc(m, typ.skipModifier)
if isImportedType(typ) and result != "":
useHeader(m, typ.sym)
result = typ.sym.loc.snippet
of tyStatic:
if typ.n != nil: result = getSimpleTypeDesc(m, skipModifier typ)
else:
Expand Down Expand Up @@ -861,7 +866,8 @@ proc getTypeDescAux(m: BModule; origTyp: PType, check: var IntSet; kind: TypeDes
if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
let sig = hashType(origTyp, m.config)

result = getTypePre(m, t, sig)
# tyDistinct matters if it is an importc type
result = getTypePre(m, origTyp.skipTypes(irrelevantForBackend-{tyOwned, tyDistinct}), sig)
defer: # defer is the simplest in this case
if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
addAbiCheck(m, t, result)
Expand Down
13 changes: 13 additions & 0 deletions tests/ccgbugs/timportc_distinct.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
discard """
ccodecheck: "time_t"
joinable: false
"""

type
Time* {.importc: "time_t", header: "<time.h>".} = distinct clong

proc foo =
var s: Time = default(Time)
discard s

foo()

0 comments on commit 8be82c3

Please sign in to comment.