Commit Graph

1836 Commits

Author SHA1 Message Date
Andreas Rumpf
80cf9a8ce8 system.nim: memory must be part of system so that its compilerprocs c… (#25365)
…an work for IC
2025-12-18 04:53:09 +01:00
ringabout
e1f2329e55 fixes #25329; Wrong type for second parameter of procedures "inc", "dec", "succ" and "pred" (#25337)
fixes #25329
2025-12-09 07:16:23 +01:00
Andreas Rumpf
fa4d79f519 IC: progress (#25339) 2025-12-07 13:07:44 +01:00
ringabout
0ea5f2625c fixes #25306; Dangling pointers in stack traces with -d:nimStackTraceOverride (#25313)
fixes #25306

```nim
type
  StackTraceEntry* = object ## In debug mode exceptions store the stack trace that led
                            ## to them. A `StackTraceEntry` is a single entry of the
                            ## stack trace.
    procname*: cstring      ## Name of the proc that is currently executing.
    line*: int              ## Line number of the proc that is currently executing.
    filename*: cstring      ## Filename of the proc that is currently executing.
    when NimStackTraceMsgs:
      frameMsg*: string     ## When a stacktrace is generated in a given frame and
                            ## rendered at a later time, we should ensure the stacktrace
                            ## data isn't invalidated; any pointer into PFrame is
                            ## subject to being invalidated so shouldn't be stored.
    when defined(nimStackTraceOverride):
      programCounter*: uint ## Program counter - will be used to get the rest of the info,
                            ## when `$` is called on this type. We can't use
                            ## "cuintptr_t" in here.
      procnameStr*, filenameStr*: string ## GC-ed alternatives to "procname" and "filename"
```
2025-12-05 07:52:35 +01:00
ringabout
5d4829415a fixes #25324; Channel incorrectly takes a sink argument in refc (#25328)
… it performs a deep copy internally

fixes #25324

notes that
> Enabling `-d:nimPreviewSlimSystem` removes the import of
`channels_builtin` in
in the `system` module, which is replaced by
[threading/channels](https://github.com/nim-lang/threading/blob/master/threading/channels.nim).
2025-12-05 00:46:47 +01:00
Jacek Sieka
91febf1f4c Ensure channels don't leak exception effects (#25318)
The forward declarations cause `Exception` to be inferred - also,
`llrecv` is an internal implementation detail and the type of the
received item is controlled by generics, thus the ValueError raised
there seems out of place for the generic api.
2025-12-01 22:59:26 +01:00
Andreas Rumpf
a773178e2b IC: progress (#25314) 2025-12-01 22:59:12 +01:00
Andreas Rumpf
0486a2df51 IC progress (#25283)
bugfix: produce the required nimcache subdir
2025-11-25 12:49:23 +01:00
Andreas Rumpf
0f7b378467 system.nim refactorings for IC (#25295)
Generally useful refactoring as it produces better code.
2025-11-19 16:27:31 +01:00
Zoom
b539adf829 std: sysstr cleanup, add docs (#25180)
- Removed redundant `len` and `reserved` sets already performed by prior
`rawNewStringNoInit` calls.
- Reuse `appendChar`
- Removed never used `newOwnedString`
- Added internal `toOwnedCopy`
- Documents differences in impls of internal procs used for
`system.string.setLen`:
  + `strs_v2.setLengthStrV2`:
    - does not set the terminating zero byte when new length is 0
    - does not handle negative new length
  + `sysstr.setLengthStr`:
    - sets the terminating zero byte when new length is 0
    - bounds negative new length to 0
2025-11-15 08:42:10 +01:00
Zoom
01c084077e std: sysstr refactor (#25185)
Continuation of #25180. This one refactors the sequence routines.

Preparation for extending with new routines.

Mostly removes repeating code to simplify debugging.

Removes:
 - `incrSeqV2` superseded by `incrSeqV3`,
 - `setLengthSeq` superseded by `setLengthSeqV2`

Note comment on line 338, acknowledging that implementation of
`setLenUninit` from #25022 does zero the new memory in this branch,
having been copied from `setLengthSeqV2`. This PR does not fix this.
2025-11-15 08:41:57 +01:00
metagn
839cbeb371 js: replace push.apply with for loop for string add [backport] (#25267)
While `a.push.apply(a, b)` is better for performance than the previous
`a = a.concat(b)` due to the fact that it doesn't create a new array,
there is a pretty big problem with it: depending on the JS engine, if
the second array is too long, it can [cause a
crash](https://tanaikech.github.io/2020/04/20/limitation-of-array.prototype.push.apply-under-v8-for-google-apps-script/)
due to the function `push` taking too many arguments. This has
unfortunately been what the codegen produces since 1.4.0 (commit
707367e1ca).

So string addition is now moved to a compilerproc that just uses a `for`
loop. From what I can tell this is the most compatible and the fastest.
Only potential problem compared to `concat` etc is with aliasing, i.e.
adding an array to itself, but I'm guessing it's enough that the length
from before the iteration is used, since it can only grow. The test
checks for aliased nim strings but I don't know if there's an extra
protection for them.
2025-11-07 20:19:50 +08:00
Jacek Sieka
861ebc0f19 Add heaptrack support (#25257)
This PR, courtesy of @NagyZoltanPeter
(https://github.com/waku-org/nwaku/pull/3522) adds the ability to track
memory allocations in a program suitable for use with
[heaptrack](https://github.com/KDE/heaptrack).

By passing `-d:heaptrack --debugger:native` to compilation, calls to
heaptrack will be injected when memory is being allocated and released -
unlike `-d:useMalloc` this strategy also works with `refc` and the
default memory pool.

See https://github.com/KDE/heaptrack for usage examples. The resulting
binary needs to be run with `heaptrack` and with the shared
`libheaptrack_preload.so` in the `LD_LIBRARY_PATH`.
2025-11-06 17:33:52 +01:00
Yuriy Glukhov
7af4e3eefd Fixes #25202 (#25244) 2025-10-28 12:48:22 +01:00
ringabout
87ee9c84cb makes DuplicateModuleImport back to an error (#25178)
fixes #24998

Basically it retraces back to the situation before
https://github.com/nim-lang/Nim/pull/18366 and
https://github.com/nim-lang/Nim/pull/18362, i.e.

```nim
import fuzz/a
import fuzz/a
```

```nim
import fuzz/a
from buzz/a
```

```nim
import fuzz/a except nil
from fuzz/a import addInt
```

All of these cases are now flagged as invalid and triggers a
redefinition error, i.e., each module name importing is treated as
consistent as the symbol definition


kinda annoying for importing/exporting with `when conditions` though

ref https://github.com/nim-lang/Nim/issues/18762
https://github.com/nim-lang/Nim/issues/20907

```nim
from std/strutils import toLower
when not defined(js):
  from std/strutils import toUpper
```
2025-09-18 20:50:46 +02:00
Jacek Sieka
41ce86b577 Remove Nim signal handler for SIGINT (#25169)
Inside a signal handler, you cannot allocate memory because the signal
handler, being implemented with a C
[`signal`](https://en.cppreference.com/w/c/program/signal) call, can be
called _during_ a memory allocation - when that happens, the CTRL-C
handler causes a segfault and/or other inconsistent state.

Similarly, the call can happen from a non-nim thread or inside a C
library function call etc, most of which do not support reentrancy and
therefore cannot be called _from_ a signal handler.

The stack trace facility used in the default handler is unfortunately
beyond fixing without more significant refactoring since it uses
garbage-collected types in its API and implementation.

As an alternative to https://github.com/nim-lang/Nim/pull/25110, this PR
removes the most problematic signal handler, namely the one for SIGINT
(ctrl-c) - SIGINT is special because it's meant to cause a regular
shutdown of the application and crashes during SIGINT handling are both
confusing and, if turned into SIGSEGV, have downstream effects like core
dumps and OS crash reports.

The signal handlers for the various crash scenarios remain as-is - they
may too cause their own crashes but we're already going down in a bad
way, so the harm is more limited - in particular, crashing during a
crash handler corrupts `core`/crash dumps. Users wanting to keep their
core files pristine should continue to use `-d:noSignalHandler` - this
is usually the better option for production applications since they
carry more detail than the Nim stack trace that gets printed.

Finally, the example of a ctrl-c handler performs the same mistake of
calling `echo` which is not well-defined - replace it with an example
that is mostly correct (except maybe for the lack of `volatile` for the
`stop` variable).
2025-09-17 10:58:21 +02:00
Jacek Sieka
40fe59b6ef remove alloc cruft (#25170) 2025-09-15 15:09:42 +02:00
Jacek Sieka
8b9972c8b6 orc: fix overflow checking regression (#25089)
Raising exceptions halfway through a memory allocation is undefined
behavior since exceptions themselves require multiple allocations and
the allocator functions are not reentrant.

It is of course also expensive performance-wise to introduce lots of
exception-raising code everywhere since it breaks many optimisations and
bloats the code.

Finally, performing pointer arithmetic with signed integers is incorrect
for example on on a 32-bit systems that allows up to 3gb of address
space for applications (large address extensions) and unnecessary
elsewhere - broadly, stuff inside the memory allocator is generated by
the compiler or controlled by the standard library meaning that
applications should not be forced to pay this price.

If we wanted to check for overflow, the right way would be in the
initial allocation location where both the size and count of objects is
known.

The code is updated to use the same arithmetic operator style as for
refc with unchecked operations rather than disabling overflow checking
wholesale in the allocator module - there are reasons for both, but
going with the existing flow seems like an easier place to start.
2025-09-15 15:08:21 +02:00
ringabout
611b8bbf67 fixes #25007; implements setLenUninit for refc (#25022)
fixes #25007

```nim
proc setLengthSeqUninit(s: PGenericSeq, typ: PNimType, newLen: int, isTrivial: bool): PGenericSeq {.
    compilerRtl.} =
```

In this added function, only the line `zeroMem(dataPointer(result,
elemAlign, elemSize, newLen), (result.len-%newLen) *% elemSize)` is
removed from `proc setLengthSeqV2` when enlarging a sequence.

JS and VM versions simply use `setLen`.
2025-07-14 23:19:58 +02:00
Yuriy Glukhov
36f8cefa85 Fixes #21235, #23602, #24978, #25018 (#25030)
Reworked closureiter transformation.

- Convolutedly nested finallies should cause no problems now.
- CurrentException state now follows nim runtime rules (pushes and pops
appropriately), and mimics normal code, which is somewhat buggy, see
#25031
- Previously state optimization (removing empty states or extra jumps)
missed some opportunities, I've reimplemented it to do everything
possible to optimize the states. At this point any extra states or jumps
should be considered a bug.

The resulting codegen (compiled binaries) is also slightly smaller.


**BUT:**
- I had to change C++ reraising logic, see expt.nim. Because with
closure iters `currentException` is not always in sync with C++'s notion
of current exception. From my tests and understanding of C++ runtime
there should not be any problems, but I'm only 99% sure :)
- I've reused `nfNoRewrite` flag in one specific case during the
transformation. This flag is also used in term-rewriting logic. Again,
99% sure, these 2 scenarios will never intersect.
2025-07-08 15:41:17 +02:00
Zoom
6bdb069a66 [docs]: warning for long, culong being OS-dependent (#25012)
Docs are routinely compiled on a different OS so often don't reflect
reality of CT-conditionals.

I bet there's a few of other places like this in the stdlib.
2025-06-27 10:49:02 +02:00
Jacek Sieka
aba9361510 Ensure that gc interface remains non-raising (#25006)
GC_fullCollect in particular has an annoying `Exception` effect
2025-06-18 14:38:01 +02:00
Eugene Kabanov
7a53db6874 Fix FreeBSD getThreadId() should use different syscall definition for 64bit platforms. (#24977) 2025-06-05 14:30:07 +02:00
Andreas Rumpf
1e602490e9 fixes #4851 [backport] (#24954) 2025-05-16 09:44:13 +02:00
metagn
97d819a251 add bit type overloads of $ and repr (#24865)
fixes #24864
2025-04-12 08:37:36 +02:00
ringabout
26b86c8f4d Makes except: panics on Defect (#24821)
implements https://github.com/nim-lang/RFCs/issues/557


It inserts defect handing into a bare except branch

```nim
try:
  raiseAssert "test"
except:
  echo "nope"
```

=>

```nim
try:
  raiseAssert "test"
except:
  # New behaviov, now well-defined: **never** catches the assert, regardless of panic mode
  raiseDefect()
  echo "nope"
```

In this way, `except` still catches foreign exceptions, but panics on
`Defect`. Probably when Nim has `except {.foreign.}`, we can extend
`raiseDefect` to foreign exceptions as well. That's supposed to be a
small use case anyway.

 `--legacy:noPanicOnExcept` is provided for a transition period.
2025-04-03 16:09:58 +02:00
ringabout
d15705e05b fixes usenimrtl with useMalloc (#24804)
Follow up https://github.com/nim-lang/Nim/pull/19512

ref https://github.com/nim-lang/Nim/issues/24794

Otherwise, `/Users/blue/Desktop/Nim/lib/system/mm/malloc.nim(4, 1)
Error: redefinition of 'allocImpl'; previous declaration here:
/Users/blue/Desktop/Nim/lib/system/memalloc.nim(51, 8)`


In `proc allocImpl*(size: Natural): pointer {.noconv, rtl, tags: [],
benign, raises: [].}`, `rtl` means it is an `importc` function instead
of a proc forward decl.
2025-03-24 22:52:43 +01:00
ringabout
0b9ed84d32 disable implicit sinkinference for stdlibs (#24803)
ref https://github.com/nim-lang/Nim/issues/24794
2025-03-24 14:07:45 +01:00
ringabout
b421d0f8ee fixes #19728; setLen slow when shrinking seq due to zero-filling of released area (#24683)
fixes #19728

don't zero-filling memory for "trivial types" without destructor in
refc. I tested locally with internal apis.
2025-02-27 16:45:58 +01:00
ringabout
1f07fdd2dc fixes #24664; always sets the \0 terminator in appendString (#24703)
fixes #24664

```nim
proc main() = 
    for i in 0..1:
        var s = "12345"
        s.add s
        echo s

main()
```
In the given example, `add` contains two steps: `prepareAdd` and
`appendString`. In the first step, a new buffer is created in order to
store the final doubled string. But it doesn't copy the null terminator,
neither zeromem the left unused spaces. It causes a problem because
`appendString` will copy itself which doesn't end with `\0` properly so
contaminated memory is copied instead.

```
var s = 12345\0

prepareAdd:

var s = 12345xxxxx\0

appendString:

var s = 1234512345x
```
2025-02-19 23:01:56 +01:00
ringabout
510ac84518 implements quirky for functions (#24700)
ref https://github.com/nim-lang/Nim/pull/24686

With this PR

```nim
import std/streams


proc foo() =
  var name = newStringStream("2r2")
  raise newException(ValueError, "sh")

try:
  foo()
except:
 discard

echo 123
```
this example no longer leaks

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2025-02-18 17:24:41 +01:00
Antonis Geralis
6481482e0e Optimize storing into uninit locations for arrays and seqs. (#24619) 2025-01-19 16:20:54 +03:00
Jacek Sieka
e8bf6af0da fix c_memchr, c_strstr definitions (#24587)
One correct definition is enough
2025-01-02 17:28:35 +01:00
ringabout
d2d810585c fixes strictdefs warnings continue (#24520) 2024-12-13 15:04:49 +01:00
ringabout
c0861142f8 fixes strictdefs warnings for stdlibs [part two] (#24514)
After some cleanups for stdlibs, then we should enable warningaserror
for all tests
2024-12-06 05:40:48 +01:00
ringabout
8f4bfda5f4 fixes some strictdefs warnings (#24502) 2024-12-04 18:28:13 +08:00
ringabout
464dc99376 fixes devel version number (#24494)
As said in the documentation, `NimMinor` is supposed to be odd and
should be greater than the stable channel
2024-12-03 08:41:04 +01:00
ringabout
2df633180a enable experimental:strictDefs (#24225) 2024-11-23 22:01:39 +01:00
ringabout
a788bae318 remove unnecessary imports (#24465)
ref https://github.com/nim-lang/Nim/issues/24272
2024-11-21 22:10:26 +01:00
metagn
ae9287c4f3 symmetric difference operation for sets via xor (#24286)
closes https://github.com/nim-lang/RFCs/issues/554

Adds a symmetric difference operation to the language bitset type. This
maps to a simple `xor` operation on the backend and thus is likely
faster than the current alternatives, namely `(a - b) + (b - a)` or `a +
b - a * b`. The compiler VM implementation of bitsets already
implemented this via `symdiffSets` but it was never used.

The standalone binary operation is added to `setutils`, named
`symmetricDifference` in line with [hash
sets](https://nim-lang.org/docs/sets.html#symmetricDifference%2CHashSet%5BA%5D%2CHashSet%5BA%5D).
An operator version `-+-` and an in-place version like `toggle` as
described in the RFC are also added, implemented as trivial sugar.
2024-10-19 10:07:00 +02:00
ringabout
95a7695810 documentation and comments use HTTPS when possible (#24264) 2024-10-08 21:50:35 +02:00
Tomohiro
d6633ae1da Change how to multiply 1.5 to ints to reduce overflow (#24257) 2024-10-07 23:18:11 +02:00
Miran
d6a71a1067 bump NimVersion to 2.2.1 (#24215) 2024-10-02 22:02:17 +02:00
Miran
a5f46a72ba bump NimVersion to 2.2.0 (#24210) 2024-09-30 20:59:38 +02:00
metagn
04ccd2f4f0 revert second argument of inc not being generic (#24129)
refs #22328, fixes regression in
https://forum.nim-lang.org/t/12465#76998
2024-09-17 21:28:54 +02:00
metagn
cd22560af5 fix string literal assignment with different lengths on ARC (#24083)
fixes #24080
2024-09-08 20:17:26 +02:00
metagn
d3af51e3ce remove fauxMatch for tyFromExpr, remove tyProxy and tyUnknown aliases (#24018)
updated version of #22193

After #22029 and the followups #23983 and #24005 which fixed issues with
it, `tyFromExpr` no longer match any proc params in generic type bodies
but delay all non-matching calls until the type is instantiated.
Previously the mechanism `fauxMatch` was used to pretend that any
failing match against `tyFromExpr` actually matched, but prevented the
instantiation of the type until later.

Since this mechanism is not needed anymore for `tyFromExpr`, it is now
only used for `tyError` to prevent cascading errors and changed to a
bool field for simplicity. A change in `semtypes` was also needed to
prevent calling `fitNode` on default param values resolving to type
`tyFromExpr` in generic procs for params with non-generic types, as this
would try to coerce the expression into a concrete type when it can't be
instantiated yet.

The aliases `tyProxy` and `tyUnknown` for `tyError` and `tyFromExpr` are
also removed for uniformity.
2024-08-28 20:46:36 +02:00
Miran
4c250d69a8 bump NimVersion to 2.1.99 (2.0.2 RC2) (#24016) 2024-08-27 02:49:46 +02:00
Antonis Geralis
c0aa951ee0 Fixed nimscript docs (#23938) 2024-08-11 10:35:09 +08:00
Tomohiro
12b9680291 Add a document to toOpenArray proc (#23905) 2024-08-01 12:27:10 +08:00