Commit Graph

1825 Commits

Author SHA1 Message Date
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
ringabout
39629a1adc fixes JS semicolon omissions (#23896) 2024-07-26 20:45:52 +02:00
SirOlaf
881fbb8f81 Allocator: Always place free cells into the active chunk and add documentation (#23871)
Lets single threaded applications benefit from tracking foreign cells as
well.
After this, `SmallChunk` technically doesn't need to act as a linked
list anymore I think, gotta investigate that more though.
The likelihood of overflowing `chunk.free` also rises, so to work around
that it might make sense to check `foreignCells` instead of adjusting
free space or replace free with a counter for the local capacity.

For Nim compile I can observe a ~10mb reduction, and smaller ones for
other projects.
2024-07-22 16:36:46 +02:00
SirOlaf
fd1e62a7e2 Allocator: Track number of foreign cells a small chunk has access to (#23856)
Ref: https://github.com/nim-lang/Nim/issues/23788

There was a small leak in the above issue even after fixing the
segfault. The sizes of `free` and `acc` were changed to 32bit because
adding the `foreignCells` field will drastically increase the memory
usage for programs that hold onto memory for a long time if they stay as
64bit.
2024-07-20 05:40:00 +02:00
Antonis Geralis
ad5b5e3ec0 Add warnings about exec usage. (#23820)
Related to https://github.com/nim-lang/Nim/issues/23819 and also found
in discord
https://discord.com/channels/371759389889003530/371759389889003532/1260845467147829372
Since nothing can be done, besides deprecating the function, a warning
is a better option.

---------

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2024-07-17 08:45:52 +02:00
Miran
f6aeca5765 bump NimVersion to 2.1.9 (#23831)
This is a 2.2 RC1.
2024-07-12 21:06:29 +02:00
SirOlaf
3f5016f60e Adjust the correct chunk's free space in allocator (#23795)
Fixes #23788
2024-07-08 11:15:53 +02:00
Andreas Rumpf
8096fa45bd fixes #23725; Size computations work better when they are correct (#23758)
[backport]
2024-06-26 05:09:05 +02:00
ringabout
2bef08774f fixes #23742; setLen(0) no longer allocates memory for uninitialized strs/seqs for refc (#23745)
fixes #23742

Before my PR, `setLen(0)` doesn't free buffer if `s != nil`, but it
allocated unnecessary memory for `strs`. This PR rectifies this
behavior. `setLen(0)` no longer allocates memory for uninitialized
strs/seqs
2024-06-21 15:07:45 +02:00
Andreas Rumpf
3770236bee fixes #22927; no test case extractable [backport] (#23707) 2024-06-12 14:27:49 +02:00
Andreas Rumpf
69d0b73d66 fixes #22510 (#23100) 2024-06-06 00:52:01 +02:00
ringabout
d923c581c1 revert #23436; remove workaround (#23653)
revert #23436
2024-05-28 20:40:41 +08:00