adds nimPreviewCStringComparisons for cstring comparisons (#24946)

todo: We can also give a deprecation message for `ltPtr`/`lePtr`
matching for cstring in `magicsAfterOverloadResolution`

follow up https://github.com/nim-lang/Nim/pull/24942
This commit is contained in:
ringabout
2025-05-15 03:31:53 +08:00
committed by GitHub
parent c1e6cf812f
commit ade500b2cb
4 changed files with 31 additions and 25 deletions

View File

@@ -21,6 +21,8 @@ errors.
- The bare `except:` now panics on `Defect`. Use `except Exception:` or `except Defect:` to catch `Defect`. `--legacy:noPanicOnExcept` is provided for a transition period.
- With `-d:nimPreviewCStringComparisons`, comparsions (`<`, `>`, `<=`, `>=`) between cstrings switch from reference semantics to value semantics like `==` and `!=`.
## Standard library additions and changes
[//]: # "Additions:"

View File

@@ -11,6 +11,7 @@ define:nimPreviewRangeDefault
define:nimPreviewNonVarDestructor
define:nimPreviewCheckedClose
define:nimPreviewAsmSemSymbol
define:nimPreviewCStringComparisons
threads:off
#import:"$projectpath/testability"

View File

@@ -2738,36 +2738,37 @@ func ltCStringVm(x, y: cstring): bool {.inline.} =
func leCStringVm(x, y: cstring): bool {.inline.} =
discard "implemented in the vm ops"
func `<`*(x, y: cstring): bool {.inline.} =
if x == y:
result = false
elif x == nil:
result = true
elif y == nil:
result = false
else:
when nimvm:
result = ltCStringVm(x, y)
when defined(nimPreviewCStringComparisons):
func `<`*(x, y: cstring): bool {.inline.} =
if x == y:
result = false
elif x == nil:
result = true
elif y == nil:
result = false
else:
when defined(js):
result = pointer(x) < pointer(y)
when nimvm:
result = ltCStringVm(x, y)
else:
result = strcmp(x, y) < 0
when defined(js):
result = pointer(x) < pointer(y)
else:
result = strcmp(x, y) < 0
func `<=`*(x, y: cstring): bool {.inline.} =
if x == y: result = true
elif x == nil:
result = true
elif y == nil:
result = false
else:
when nimvm:
result = leCStringVm(x, y)
func `<=`*(x, y: cstring): bool {.inline.} =
if x == y: result = true
elif x == nil:
result = true
elif y == nil:
result = false
else:
when defined(js):
result = pointer(x) <= pointer(y)
when nimvm:
result = leCStringVm(x, y)
else:
result = strcmp(x, y) <= 0
when defined(js):
result = pointer(x) <= pointer(y)
else:
result = strcmp(x, y) <= 0
template closureScope*(body: untyped): untyped =
## Useful when creating a closure in a loop to capture local loop variables by

View File

@@ -46,3 +46,5 @@ when not defined(testsConciseTypeMismatch):
switch("experimental", "vtables")
switch("experimental", "openSym")
switch("experimental", "typeBoundOps")
switch("define", "nimPreviewCStringComparisons")