Commit Graph

23018 Commits

Author SHA1 Message Date
Nils-Hero Lindemann
f0c60b06e5 Update outdated string representation in example (#25802)
See
[here](https://nim-lang.github.io/Nim/tut1.html#internal-type-representation).
2026-05-09 08:55:39 +02:00
Ryan McConnell
4c8052a45b fix: implicit imports drop std/ prefix (#25780)
Preserves implicit imports instead of always storing the resolved
absolute filename. That lets the later StdPrefix warning check see the
original std/objectdollar spelling.

This is for situations where in cfg or cli warnings are enabled for the
prefix. Essentially a niche combination of compiler switches don't get
along e.g.

`-d:nimPreviewSlimSystem --warning:StdPrefix:on
--warningAsError:StdPrefix:on --import:std/objectdollar`

will cause:

`Error: objectdollar needs the 'std' prefix [StdPrefix]`
2026-05-08 06:50:13 +02:00
Nils-Hero Lindemann
7295f57833 Write all variables italic in section "About this document" (#25797)
Makes more sense. One variable was already written italic.
2026-05-08 06:48:48 +02:00
Andreas Rumpf
f0077a12b2 fixes DOS via malformed HTTP protocol (#25793)
refs https://github.com/nim-lang/Nim/pull/25568
2026-05-06 19:48:08 +08:00
ringabout
568eccd7f8 fixes #25617; handle backend type aliasing in procParamTypeRel (#25692)
fixes #25617

This pull request introduces a stricter check for parameter type
relations in the `procParamTypeRel` procedure. Specifically, it ensures
that two types are not only structurally equal but also have the same
backend type, taking type aliases into account.

Type relation checks:

*
[`compiler/sigmatch.nim`](diffhunk://#diff-251afcd01d239369019495096c187998dd6695b6457528953237a7e4a10f7138R787-R789):
In `procParamTypeRel`, added a check to ensure that if two types are
considered equal (`isEqual`), they must also have the same backend type
(using `sameBackendTypePickyAliases`). If not, the result is set to
`isNone`, preventing false positives when type aliases differ.
2026-05-06 08:44:09 +02:00
ringabout
f2e4ae0016 fixes lent tuple codegen error (#25782)
ref https://github.com/nim-lang/Nim/pull/25783

This pull request addresses an issue with addressability of tuple
elements of type `lent` or `var` in Nim, ensuring that expressions
involving these types are handled correctly during type changes. The
main changes introduce a check to prevent attempting to change the type
of tuple elements that are views (`var` or `lent`), and a new test is
added to verify the correct error is raised when trying to take the
address of such elements.

Type system and semantic analysis improvements:

* Added the `isViewTarget` template in `semexprs.nim` to check if a type
is a view (`var` or `lent`), and updated `changeType` to skip type
changes for tuple elements that are views. This prevents invalid
addressability operations on these types.
[[1]](diffhunk://#diff-539da3a63df08fa987f1b0c67d26cdc690753843d110b6bf0805a685eeaffd40R655-R657)
[[2]](diffhunk://#diff-539da3a63df08fa987f1b0c67d26cdc690753843d110b6bf0805a685eeaffd40R686-R693)

Testing:

* Added a new test `tlent_tuple_address.nim` to verify that attempting
to take the address of tuple elements of type `lent` correctly produces
an "expression has no address" error.
2026-05-06 08:42:36 +02:00
Andreas Rumpf
df7a114d7a IC: use the newer nif27 format (#25792) 2026-05-06 08:41:59 +02:00
ringabout
e9a0c9634e fixes #25784; Object default field initialized with an object constructor (#25785)
fixes #25784

This pull request addresses the handling of forward object types during
type determination in the Nim compiler and adds new test cases to ensure
correct default value initialization for objects with forward
references. The main focus is to allow forward object types to remain
unresolved during the initial type analysis, deferring their resolution
to a later compilation phase. This helps support object constructors
with default values involving forward types.

**Compiler improvements:**

* Updated `semObjConstr` in `compiler/semobjconstr.nim` to allow forward
object types (`tyForward`) to remain unresolved during determine-type
analysis. This avoids premature errors and ensures that such types are
resolved later, supporting delayed field-default resolution.

**Testing enhancements:**

* Added new test cases in `tests/objects/mobject_default_value.nim` to
verify that objects with default fields referencing forward types are
correctly initialized, and that their default values are properly set.

---------

Co-authored-by: Copilot <copilot@github.com>
2026-05-05 21:05:17 +02:00
ringabout
b73908a361 fix #25789; improve handling of distinct types (#25791)
fix #25789

This pull request addresses an issue with the `distinctBase` trait in
the Nim compiler, ensuring it correctly handles types with generic
parameters and static parameters. Additionally, it adds a new test to
cover this scenario. The most important changes are:

### Compiler logic improvements

* Updated the `evalTypeTrait` implementation for the `distinctBase`
trait in `compiler/semmagic.nim` to properly skip all relevant type
wrappers, including those with generic and static parameters, when
unwrapping distinct types. This fixes incorrect handling of types like
`distinct L[int, 100]`.

### Test coverage

* Added a new test block for bug #25789 in
`tests/metatype/ttypetraits.nim` that defines a distinct type over a
generic type with a static parameter, verifies conversions, and checks
that the `distinctBase` trait returns the correct type.
2026-05-05 20:21:37 +02:00
puffball1567
cbe02aa9de fixes finally being skipped when except T as e re-raises (cpp backend) (#25775)
## Bug

When an `except T as e:` handler in the cpp backend raises a new
exception, the enclosing `finally` block is silently dropped under
`--mm:arc` and `--mm:orc`:

```nim
proc main() =
  try:
    try:
      raise newException(CatchableError, "orig")
    except CatchableError as e:
      echo "inner: ", e.msg
      raise newException(CatchableError, "re:" & e.msg)
    finally:
      echo "finally"
  except CatchableError as outer:
    echo "outer: ", outer.msg

main()
```

Expected output:
```
inner: orig
finally
outer: re:orig
```

Actual output on `nim cpp --mm:arc` (and `--mm:orc`):
```
inner: orig
outer: re:orig
```

The `finally` line is missing. The bug is specific to memory managers
that use destructor injection (arc/orc); under `--mm:refc` the original
code path works correctly because no destructor wrapper is injected.

## Root cause

When the body of `except T as e:` is processed under ARC/ORC, the
destructor injection pass injects a compiler-generated `nkHiddenTryStmt`
wrapper around the handler body to call `=destroy` on `e` when it goes
out of scope. That wrapper sits at the top of `p.nestedTryStmts` with
`inExcept = false`.

`finallyActions` (which inlines the user-finally body before a raise
propagates) only inspected the topmost entry of `nestedTryStmts`.
Because the wrapper has `inExcept = false`, the check short-circuited
and the user's finally was never inlined.

After the raise, C++'s rule that sibling catch clauses do not catch each
other's throws means the surrounding `catch(...)/finally` emitted by
`genTryCpp` never runs either, so the user's finally is silently
dropped.

## Fix

- Add an `isHidden` flag to `nestedTryStmts` entries, set to `t.kind ==
nkHiddenTryStmt` so compiler-injected try wrappers can be distinguished
from user-written ones.
- In `finallyActions`, walk past `isHidden` wrappers but stop at the
first user try. If that user try is in its except branch with a finally,
inline the finally body before the raise; otherwise leave the raise
untouched (the raise will be caught by that user try's own except
branches and the inner finally will run via normal unwinding, which is
what already happens correctly under refc).

Walking past wrappers fixes the `as e` case under arc/orc. Stopping at
user trys preserves the existing correct behaviour for nested
try/except/finally constructs (e.g. `tests/exception/tfinally.nim`'s
`nested_finally`), which would otherwise see the outer finally inlined
too eagerly when an inner raise is processed.

## Tests

Adds `tests/exception/tcpp_handler_raise_finally.nim` covering:

- `except T as e:` re-raise + outer finally
- typeless `except:` re-raise + outer finally
- try/finally without except (exception propagation through finally)

The test runs on `--mm:arc`, `--mm:orc`, and `--mm:refc`.

Locally verified on both `devel` and `version-2-2`:

- `tests/exception/` — 42 PASS, 0 FAIL, 3 SKIP
- `tests/destructor/` — all PASS
- `tests/cpp/` — all PASS (single unrelated failure: `tasync_cpp.nim`
needs the `jester` package)
- `megatest` — PASS for both `--mm:arc` and `--mm:refc`, including the
previously regressing `tfinally.nim`'s `nested_finally`

## Backport

Tagged `[backport]` in the commit message for inclusion in
`version-2-2`.

---------

Co-authored-by: puffball1567 <17452514+puffball1567@users.noreply.github.com>
2026-05-05 21:27:33 +08:00
Andreas Rumpf
4bcb706d49 IC: added support for conditional dependencies (#25770) 2026-04-28 18:48:41 +02:00
ringabout
92d0c097e5 fixes #25140; Cannot resolve pragmas when new type is defined from typeof expression (#25764)
fixes #25140
2026-04-27 18:47:45 +02:00
Andreas Rumpf
49b5e66d3a SSO: better switch to enable it (#25772) 2026-04-27 18:00:29 +02:00
Zoom
cbe8ce59ed fix string setLenUninit growth without realloc for refc (#25767)
`setLenUninit(string)` was broken on the legacy refc backend when
growing within existing spare capacity.

`setLengthStrUninit` in `lib/system/sysstr.nim` only updated len when it
had to reallocate or when shrinking.

If oldLen < newLen <= capacity, it returned early without finalizing:

```nim
var s = newStringOfCap(10)
s.add("abc")
s.setLenUninit(6)
doAssert s.len == 6 # used to fail, len stayed 3
```

This escaped `tests/stdlib/tstring.nim` because the testing routine
`checkSetLenUninit` mostly resizes strings created at **exact**
length/capacity, so growth usually took the reallocating branch.

The new regression test covers the missing edge case.

So sorry for catching this only on the day of the stable release! In my
defense, the original PR hung in limbo for quite a while and it didn't
spend enough time in devel after the merge.
2026-04-25 12:27:13 +02:00
Jake Leahy
148e82f418 Add Nix certificate path to ssl_certs.nim (#25763)
This makes it easier to run Nix built containers for Nim programs since
by default Nim doesn't search environment variables for SSL certs so its
a little annoying having to move around files

-
10e7ad5bbc/pkgs/by-name/ca/cacert/package.nix (L85)
2026-04-24 14:04:30 +02:00
Tomohiro
8b44b9d9ae fixes #23668; Create a new std/nre2 module using Nim Regex replaces re and nre (#25696)
std/nre2 is implemented using https://github.com/nitely/nim-regex.
std/nre2 has almost same features as std/nre but some regular
expressions supported by std/nre are not supported.
The syntax of regular expressions of Nim Regex is explained in:
https://nitely.github.io/nim-regex/regex.html
2026-04-22 08:06:03 +02:00
ringabout
efacf1f390 Fix typo in getContentType function in cgi.nim (#25757)
This pull request fixes a typo in the `getContentType` function in
`lib/pure/cgi.nim`, ensuring it retrieves the correct `CONTENT_TYPE`
environment variable.

> Exact spelling matters: It is CONTENT_TYPE, not CONTENT_Type or
Content-Type. Environment variables in CGI are case-sensitive.
2026-04-21 16:38:56 +02:00
ringabout
60bb9c75cc fixes #25650; nim ic import std/strbasics (#25760)
fixes #25650

This pull request refactors and improves the dependency resolution logic
in the Nim compiler, The most important changes are grouped below:

### Dependency Resolution Refactor

* Replaced the `resolveFile` procedure with two more specialized
procedures: `resolveImport` (which uses the compiler's module lookup
rules for imports) and `resolveInclude` (which resolves includes
relative to the including file or search paths). Updated all usages
accordingly, improving clarity and correctness of dependency handling.
[[1]](diffhunk://#diff-1203947eecb9ef641ce7ee029677f875eb983de050b82c65ca286517feed00e6L82-R94)
[[2]](diffhunk://#diff-1203947eecb9ef641ce7ee029677f875eb983de050b82c65ca286517feed00e6L106-R103)
[[3]](diffhunk://#diff-1203947eecb9ef641ce7ee029677f875eb983de050b82c65ca286517feed00e6L121-R118)
* Removed the unused `strutils` import from `compiler/deps.nim` for
cleaner dependencies.


### Testing Improvements

* Added `import std/strbasics` to `tests/ic/tmiscs.nim` to ensure
required symbols are available for tests.


I tried to improve `resolveFile`, which is harder because either we need
to add `lib/std` to search path and all of other nested directory to
`--path` in `config/nim.cfg`. So I choose toi reuse `findModule` for
imports
2026-04-21 16:38:33 +02:00
Bojun Chai
de3d61f15b Fix invalid Mac OS X minimum version in README (#25758)
**Repo:** nim-lang/Nim ( 16000)
**Type:** docs
**Files changed:** 1
**Lines:** +1/-1

## What
Correct the supported platform table in the top-level README by changing
the Mac OS X minimum version from `10.04` to `10.4`.

## Why
`10.04` is not a valid Mac OS X release number, so the existing text is
misleading for anyone reading the build and platform support guidance.
Fixing it keeps the README accurate without changing project behavior or
widening scope.

## Testing
Verified the README diff locally and confirmed the corrected `Mac OS X
(10.4 or greater)` entry appears in `readme.md`. No code or test suite
changes were needed for this docs-only patch.

## Risk
Low / documentation-only change with no runtime impact.

Co-authored-by: Bojun Chai <bojunchai@microsoft.com>
2026-04-21 08:50:13 +08:00
Tomohiro
ba4e12fb65 fixes #25753 (#25754) 2026-04-20 20:13:06 +02:00
Andreas Rumpf
f236e6a210 fixes #25695 (#25756) 2026-04-20 09:17:12 +02:00
Tomohiro
317bc10824 Makes containsOrIncl*[A](s: var PackedSet[A], key: A) proc faster (#25755)
This PR makes it faster when a number of elements is less than 34
I used following code to compare the speed of `containsOrIncl` proc.
It calls `isRecursiveStructuralType` proc defined in compiler/types.nim
that calls `containsOrIncl` with `IntSet`(= `PackedSet[int]`).
```nim
import std/[tables, monotimes, times, strformat]
import "$nim"/compiler/[astdef, ast, idents, types]

var idgen = IdGenerator(module: 0, symId: 0, typeId: 0, disambTable: initCountTable[PIdent]())

proc newType(kind: TTypeKind; son: sink PType = nil): PType =
  result = newType(kind, idgen, nil, son)

proc genNoRecursPType(len: int): PType =
  assert len > 1
  let intTyp = newType(tyInt)
  result = newType(tyRef, intTyp)
  for i in 0..<(len - 2):
    result = newType(tyRef, result)

proc test =
  var noRecursPType = genNoRecursPType(4)
  assert not isRecursiveStructuralType(noRecursPType)

test()

template measure(label: string; body: untyped): untyped =
  let
    loop = 2000
    sampling = 200
  block:
    var r {.inject.} = false
    var minT = initDuration(hours = 1)
    for i in 0 ..< sampling:
      let start = getMonoTime()
      for j in 0 ..< loop:
        body
      let finish = getMonoTime()
      minT = min(finish - start, minT)
    echo ($r)[0], ' ', label, minT div loop

proc benchNoRecurs(len: int) =
  echo fmt"No recursive: length: {len}"
  var noRecursPType = genNoRecursPType(len)
  measure("IntSet: "):
    r = isRecursiveStructuralType(noRecursPType)

proc bench =
  benchNoRecurs(30)

bench()
```

Output before changing code:
```
f IntSet: 1 microsecond and 262 nanoseconds
```
Output after change:
```
f IntSet: 833 nanoseconds
```

Why this PR make it faster:
```nim
proc containsOrIncl*[A](s: var PackedSet[A], key: A): bool =
  ...
  if s.elems <= s.a.len:
    for i in 0..<s.elems:
      if s.a[i] == ord(key):
        return true
    # `incl` scans `s.a` again
    incl(s, key)
    result = false
```

```nim
proc containsOrIncl*[A](s: var PackedSet[A], key: A): bool =
  ...
  if s.elems <= s.a.len:
    for i in 0..<s.elems:
      if s.a[i] == ord(key):
        return true
    if s.elems < s.a.len:
      # put `key` in `s.a` instead of calling `incl(s, key)`
      s.a[s.elems] = ord(key)
      inc(s.elems)
    else:
      incl(s, key)
    result = false
```
2026-04-20 09:21:46 +08:00
ringabout
5948dbbeed fixes #25718; setLenUnit slow (#25743)
fixes #25718

This pull request optimizes sequence allocation in the Nim standard
library by introducing a way to create uninitialized sequence payloads
for element types that don't require zero-initialization. The changes
allow for more efficient memory allocation when initializing sequences
with types that have no references, avoiding unnecessary zeroing of
memory.

Sequence allocation and initialization improvements:

* Added the `newSeqUninitRaw` procedure to create sequence payloads with
a specified length without forcing zero-initialization for element types
marked as `ntfNoRefs`. (`lib/system/sysstr.nim`,
[lib/system/sysstr.nimR277-R292](diffhunk://#diff-bcaa1967f436ad03877f353823c08a8b4a719fe387629d33aab4bddf16534b5eR277-R292))
* Modified the `extendCapacityRaw` procedure and the `setLengthSeqImpl`
template to use `newSeqUninitRaw` when zero-initialization is not
required, controlled by the `doInit` static parameter.
(`lib/system/sysstr.nim`,
[[1]](diffhunk://#diff-bcaa1967f436ad03877f353823c08a8b4a719fe387629d33aab4bddf16534b5eR277-R292)
[[2]](diffhunk://#diff-bcaa1967f436ad03877f353823c08a8b4a719fe387629d33aab4bddf16534b5eL316-R335)
2026-04-19 20:12:01 +02:00
ringabout
98131a9fa1 fixes #25751; JS backend crashes when returning Option[T] with custom =destroy (#25752)
fixes #25751

This pull request improves the JavaScript backend code generation and
expands test coverage, particularly around temporary and loop variables,
as well as object destruction behavior. The main changes include
updating the code generator to handle more symbol kinds and adding tests
to ensure proper destruction and option handling.

**JavaScript code generation improvements:**

* Updated `genSymAddr` in `compiler/jsgen.nim` to support additional
symbol kinds, specifically `skTemp` and `skForVar`, ensuring correct
address generation for temporaries and loop variables.

**Test suite enhancements:**

* Added tests in `tests/js/test2.nim` to verify correct behavior of
option types, object destruction (`=destroy`), and to check for
backend-specific crashes. This includes printing results of
option-returning functions and confirming destruction messages.
* Updated expected output in `tests/js/test2.nim` to include results
from new tests and destruction messages, ensuring the test suite
reflects the latest code behavior.
2026-04-18 09:40:55 +02:00
Ryan McConnell
f98578ea35 fix 25667; Generic forward type confusion (#25737)
ref: #25667

drain deferred reification in a loop until there is no more work to do.
Could potentially evaluate the same deferred work more than once.

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
2026-04-18 08:52:31 +02:00
dependabot[bot]
e6e00a74a3 Bump actions/github-script from 8 to 9 (#25748)
Bumps [actions/github-script](https://github.com/actions/github-script)
from 8 to 9.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/github-script/releases">actions/github-script's
releases</a>.</em></p>
<blockquote>
<h2>v9.0.0</h2>
<p><strong>New features:</strong></p>
<ul>
<li><strong><code>getOctokit</code> factory function</strong> —
Available directly in the script context. Create additional
authenticated Octokit clients with different tokens for multi-token
workflows, GitHub App tokens, and cross-org access. See <a
href="https://github.com/actions/github-script#creating-additional-clients-with-getoctokit">Creating
additional clients with <code>getOctokit</code></a> for details and
examples.</li>
<li><strong>Orchestration ID in user-agent</strong> — The
<code>ACTIONS_ORCHESTRATION_ID</code> environment variable is
automatically appended to the user-agent string for request
tracing.</li>
</ul>
<p><strong>Breaking changes:</strong></p>
<ul>
<li><strong><code>require('@actions/github')</code> no longer works in
scripts.</strong> The upgrade to <code>@actions/github</code> v9
(ESM-only) means <code>require('@actions/github')</code> will fail at
runtime. If you previously used patterns like <code>const { getOctokit }
= require('@actions/github')</code> to create secondary clients, use the
new injected <code>getOctokit</code> function instead — it's available
directly in the script context with no imports needed.</li>
<li><code>getOctokit</code> is now an injected function parameter.
Scripts that declare <code>const getOctokit = ...</code> or <code>let
getOctokit = ...</code> will get a <code>SyntaxError</code> because
JavaScript does not allow <code>const</code>/<code>let</code>
redeclaration of function parameters. Use the injected
<code>getOctokit</code> directly, or use <code>var getOctokit =
...</code> if you need to redeclare it.</li>
<li>If your script accesses other <code>@actions/github</code> internals
beyond the standard <code>github</code>/<code>octokit</code> client, you
may need to update those references for v9 compatibility.</li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>Add ACTIONS_ORCHESTRATION_ID to user-agent string by <a
href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a
href="https://redirect.github.com/actions/github-script/pull/695">actions/github-script#695</a></li>
<li>ci: use deployment: false for integration test environments by <a
href="https://github.com/salmanmkc"><code>@​salmanmkc</code></a> in <a
href="https://redirect.github.com/actions/github-script/pull/712">actions/github-script#712</a></li>
<li>feat!: add getOctokit to script context, upgrade
<code>@​actions/github</code> v9, <code>@​octokit/core</code> v7, and
related packages by <a
href="https://github.com/salmanmkc"><code>@​salmanmkc</code></a> in <a
href="https://redirect.github.com/actions/github-script/pull/700">actions/github-script#700</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/Copilot"><code>@​Copilot</code></a> made
their first contribution in <a
href="https://redirect.github.com/actions/github-script/pull/695">actions/github-script#695</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/github-script/compare/v8.0.0...v9.0.0">https://github.com/actions/github-script/compare/v8.0.0...v9.0.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="3a2844b7e9"><code>3a2844b</code></a>
Merge pull request <a
href="https://redirect.github.com/actions/github-script/issues/700">#700</a>
from actions/salmanmkc/expose-getoctokit + prepare re...</li>
<li><a
href="ca10bbdd1a"><code>ca10bbd</code></a>
fix: use <code>@​octokit/core/</code>types import for v7
compatibility</li>
<li><a
href="86e48e20ac"><code>86e48e2</code></a>
merge: incorporate main branch changes</li>
<li><a
href="c1084728b5"><code>c108472</code></a>
chore: rebuild dist for v9 upgrade and getOctokit factory</li>
<li><a
href="afff112e4f"><code>afff112</code></a>
Merge pull request <a
href="https://redirect.github.com/actions/github-script/issues/712">#712</a>
from actions/salmanmkc/deployment-false + fix user-ag...</li>
<li><a
href="ff8117e5b7"><code>ff8117e</code></a>
ci: fix user-agent test to handle orchestration ID</li>
<li><a
href="81c6b78760"><code>81c6b78</code></a>
ci: use deployment: false to suppress deployment noise from integration
tests</li>
<li><a
href="3953caf885"><code>3953caf</code></a>
docs: update README examples from <a
href="https://github.com/v8"><code>@​v8</code></a> to <a
href="https://github.com/v9"><code>@​v9</code></a>, add getOctokit docs
and v9 brea...</li>
<li><a
href="c17d55b90d"><code>c17d55b</code></a>
ci: add getOctokit integration test job</li>
<li><a
href="a047196d9a"><code>a047196</code></a>
test: add getOctokit integration tests via callAsyncFunction</li>
<li>Additional commits viewable in <a
href="https://github.com/actions/github-script/compare/v8...v9">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/github-script&package-manager=github_actions&previous-version=8&new-version=9)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-17 19:14:36 +08:00
ringabout
c22819ef17 fixes #25732; semStaticExpr and semStaticStmt to handle errors (#25742)
fix #25732
2026-04-17 10:00:00 +02:00
ringabout
2b2872928b fixes #25469; Conversion from distinct in for forces a copy of underlying instance (#25746)
fixes #25469

This pull request introduces an important fix to argument handling in
the compiler's transformation logic and adds a new test to verify
correct behavior with distinct types and ARC memory management.

### Compiler transformation improvements

* Updated `putArgInto` in `compiler/transf.nim` to handle
`nkHiddenStdConv`, `nkHiddenSubConv`, and `nkConv` nodes more
accurately. Now, if the types match (ignoring distinctness and shallow
range differences), the argument is recursively processed; otherwise, it
falls back to a fast assignment. This prevents incorrect assignments
when dealing with type conversions and distinct types.

### Testing for distinct types and ARC

* Added a new test `tdistinct_for_nodup.nim` to ensure correct iteration
and memory management for distinct sequences of large arrays under ARC.
The test checks that the sequence length remains unchanged during
iteration, helping catch regressions related to ARC and distinct types.
2026-04-17 09:59:22 +02:00
Andreas Rumpf
b4d4028afa fixes whitespace related endless loop in renderer.nim (#25750) 2026-04-16 09:44:58 +02:00
Sai Asish Y
3eb4a60b6b ccgstmts: fix 'occured' -> 'occurred' typo in emitted C++ exception comment (#25749)
Inline C++ comment emitted by `compiler/ccgstmts.nim:1168` into
generated code read `C++ exception occured, not under Nim's control`.
Doc-only change in the emitted source.

Signed-off-by: SAY-5 <SAY-5@users.noreply.github.com>
Co-authored-by: SAY-5 <SAY-5@users.noreply.github.com>
2026-04-16 12:29:09 +08:00
ringabout
7b73537131 fixes #25735; sso C++: nimToCStringConv (#25745)
fixes #25735

This pull request updates how string-to-C-string conversions are handled
when the `nimsso` configuration flag is enabled, and adds a new system
test to validate the behavior. The main changes focus on switching from
using `addrLoc` to `byRefLoc` for argument preparation, which likely
improves correctness or compatibility with the `nimsso` mode.

**Code generation improvements for `nimsso` mode:**

* In both `compiler/ccgcalls.nim` (`genArgStringToCString`) and
`compiler/ccgexprs.nim` (`convStrToCStr`), replaced the use of `addrLoc`
with `byRefLoc` when preparing arguments for string-to-C-string
conversions under the `nimsso` configuration flag. This change ensures
that references are handled appropriately according to the requirements
of `nimsso`.
[[1]](diffhunk://#diff-42181cc6f4202af843e7835ea514df2efe85e4faae3bc797a39a0c422547b558L373-R373)
[[2]](diffhunk://#diff-4509107d295d7d32b1887c8993cd0f56113ae60f36113e7d8778646dabd92ebcL2739-R2739)

**Testing:**

* Added a new system test `tests/system/tnimsso.nim` that runs with the
`-d:nimsso` flag on both C and C++ targets, checking that
string-to-C-string conversion works as expected in `nimsso` mode.
2026-04-15 14:57:57 +02:00
Andreas Rumpf
5b1a05e282 fixes #18095 (#25744) 2026-04-14 19:58:44 +02:00
Zoom
4dbc382906 Feat: stdlib: adds system.string.setLenUninit (#24836)
Adds `system.setLenUninit` for the `string` type. Allows setting length
without initializing new memory on growth.

- Required for a follow-up to #15951
- Accompanies #22767 (ref #19727) but for strings
- Expands `stdlib/tstring` with tests for `setLen` and `setLenUninit`

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
2026-04-14 17:24:26 +02:00
Andreas Rumpf
e81f5b5890 Revert "only generate called hook for explicit or generated destructor calls [backport]" (#25741)
Reverts nim-lang/Nim#25729
2026-04-13 18:02:53 +08:00
lit
cf3c28c223 fixes #25738; std/parseopt: - causes IndexDefect (#25739) 2026-04-12 12:32:25 +02:00
Ryan McConnell
242f761627 RE: fix #25627 (#25736)
Follow up PR to #25700

@demotomohiro 

This doesn't seem to mirror your suggested approach completely. I still
went with a recursive walk. Could probably add some kind of "clean
types" and "dirty types" cache through this to minimize the recursions,
but that seems like a little much.
2026-04-12 08:56:31 +02:00
metagn
a35614e539 make explicit copy and hook calls keep their symbol (#25731)
fixes #25730

As mentioned in the issue this results in less optimized output, it
always generates the explicitly called hook as a proc rather than an
inline assignment. But maybe this is a reasonable trade since it only
happens on explicit `=sink`/`=copy` calls.

Any way to optimize it requires detecting either the type or the found
hook as a trivial assignment. I am not sure how to do these, the hook
isn't like destructors that propagate empty statements in
`liftdestructors` (which is what `isTrivial` checks for), it needs to
propagate simple assignments instead. And there is no logic for the
type, `tfHasAsgn` is misleading since it only checks if the destructor
is trivial, because there is no check for a trivial assignment.

Did not mark as backported but the only issue I can think of is the
performance issue above, otherwise it would be more correct if anything.
2026-04-12 07:05:48 +02:00
metagn
fb02e9831d only generate called hook for explicit or generated destructor calls [backport] (#25729)
fixes #25727, regression from #24627 which was backported to 2.2.2 and
2.0.16

Instead of calling `createTypeBoundOps` for explicit hook calls and when
generating default hooks, only the called destructor is generated at a
time. This allows defining more than 1 hook for recursive types.

`=sink` for `useSeqOrStrOp` and also `atomicRefOp` always need a
`=destroy` hook generated so that is also generated separately. There
might be more that I missed, only the atomicRefOp one failed `trtree` in
CI, and it was just from a compiler assert that got triggered, otherwise
it would still have functioned.
2026-04-12 07:05:11 +02:00
ringabout
6353c4e5b0 fixes #25724; Invalid C code generation with iterator/nimvm (#25728)
fixes #25724

This pull request introduces a small but important fix in the compiler
and adds a new test case related to iterators. The main change in the
compiler ensures that lambda-like constructs are handled consistently
with other procedure definitions, while the new test in the suite covers
a previously untested scenario.

**Compiler improvements:**
* Updated `introduceNewLocalVars` in `compiler/transf.nim` to handle all
`nkLambdaKinds` in addition to `nkProcDef`, `nkFuncDef`, `nkMethodDef`,
and `nkConverterDef`, ensuring consistent transformation of all
lambda-like constructs.

**Testing:**
* Added a block to `tests/iter/titer_issues.nim` to test iterator
behavior in both compile-time and run-time contexts, addressing bug
#25724.
2026-04-10 15:57:26 +02:00
ringabout
e39272eaa8 fixes #25637; nim ic with destructors (#25723)
fixes #25637

This pull request refactors the way the `sfInjectDestructors` flag is
set on symbols during lambda lifting in the Nim compiler. The main
change is the introduction of a helper procedure to encapsulate the
logic for marking symbols that require destructor injection, improving
code clarity and maintainability.

Refactoring and code quality improvements:

* Introduced the `markInjectDestructors` procedure to encapsulate the
logic for marking a symbol with the `sfInjectDestructors` flag, ensuring
that `backendEnsureMutable` is always called before modifying the
symbol's flags.
* Replaced direct flag manipulation (`owner.incl sfInjectDestructors`
and `prc.incl sfInjectDestructors`) with calls to the new
`markInjectDestructors` procedure in multiple locations, including
`makeClosure`, `createTypeBoundOpsLL`, and `rawClosureCreation`.
[[1]](diffhunk://#diff-19193904ba011a2bcc1e1a9768a7eb57cac57a274cad73d388149776ec2901e6L231-R235)
[[2]](diffhunk://#diff-19193904ba011a2bcc1e1a9768a7eb57cac57a274cad73d388149776ec2901e6L243-R247)
[[3]](diffhunk://#diff-19193904ba011a2bcc1e1a9768a7eb57cac57a274cad73d388149776ec2901e6L639-R643)
2026-04-10 15:29:20 +02:00
Ryan McConnell
2501e23d81 fixes #25290; tempalte overload scope dupe (#25308)
#25290
drafted bc if this passes full CI I am going to try and remove that
weird stuff in `pickBestCandidate`
2026-04-09 20:44:35 +02:00
ringabout
188aa1714e fixes #25719; optimizes setLenSeqCall for orc (#25721)
fixes #25719

This pull request updates the logic for resizing sequences during
certain copy operations in the `compiler/liftdestructors.nim` file. The
main improvement is that the code now distinguishes between regular and
uninitialized resizing based on whether the sequence's element type
supports bulk memory copying, which can lead to more efficient code
generation.

**Improvements to sequence resizing and copying logic:**

* Modified `setLenSeqCall` to accept a `noinit` parameter, allowing it
to choose between `setLen` and `setLenUninit` operations, and to select
the appropriate magic for each case.
* Updated `fillSeqOp` to determine if bulk memory copy is supported and,
if so, call `setLenSeqCall` with `noinit = true` and perform a bulk
copy; otherwise, it defaults to element-wise copying. This logic is now
applied in both relevant locations in the function.
[[1]](diffhunk://#diff-456118dde9a4e21f1b351fd72504d62fc16e9c30354dbb9a3efcb95a29067863L646-R650)
[[2]](diffhunk://#diff-456118dde9a4e21f1b351fd72504d62fc16e9c30354dbb9a3efcb95a29067863L661-R666)
2026-04-09 11:11:06 +02:00
Ryan McConnell
fa6b754dbc fix #25627 (#25700)
@demotomohiro this was caused by your PR please review
#25627
2026-04-09 11:09:34 +02:00
ringabout
9a2b0dd045 fixes #25697; {.borrow.} on iterator for distinct seq triggers internal error (#25709)
fixes #25697

This pull request improves the handling of borrowed routines in the
compiler transformation phase, making the code more robust and
maintainable. The main change is the introduction of a helper function
to properly resolve borrowed routine symbols, which is then used in
multiple places to ensure correct symbol resolution. Additionally, a new
test case is added to cover a previously reported bug related to
borrowed iterators on distinct types.

**Compiler improvements:**

* Added `resolveBorrowedRoutineSym` helper function to follow borrow
aliases and retrieve the underlying implementation symbol for borrowed
routines. This centralizes and clarifies the logic for resolving
borrowed symbols.
* Updated `transformSymAux` and `transformFor` to use the new helper
function, replacing duplicated logic and improving correctness when
handling borrowed routines.
[[1]](diffhunk://#diff-c7b80f51fb685eb22c5b56ee2f320d6c708706f3ae7293478ecd104a2b5b8096L139-R154)
[[2]](diffhunk://#diff-c7b80f51fb685eb22c5b56ee2f320d6c708706f3ae7293478ecd104a2b5b8096L788-R795)

**Testing:**

* Added a test case for bug #25697 to `tests/distinct/tborrow.nim`,
ensuring that iteration over a distinct type with a borrowed iterator
works as expected.
2026-04-09 11:08:03 +02:00
ringabout
c8e6b059a4 optimizes setLen for orc; disabling overflow checks (#25722)
ref https://github.com/nim-lang/Nim/issues/25695
ref https://github.com/nim-lang/Nim/pull/25715

This pull request introduces a minor but important change to the
`setLen` procedure in `lib/system/seqs_v2.nim`. The main update is the
temporary disabling of overflow checks during the initialization loop
when extending the sequence length, which can improve performance and
avoid unnecessary checks during this operation.

Memory and performance improvement:

* Disabled overflow checks for the loop that initializes new elements to
their default value when increasing the length of a sequence in
`setLen`, by wrapping the loop with `{.push overflowChecks: off.}` and
`{.pop.}`.
2026-04-09 11:07:04 +02:00
lou15b
115ec7a433 Fixes #25710 - nimsuggest outline misses methods (#25711)
This adds methods to the list generated by the `outline` command for
`nimsuggest --v3` and `nimsuggest --v4`.
The test file `tv3_outline.nim` was also updated to include a `skMethod`
line in the expected output.

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2026-04-08 00:52:12 +02:00
metagn
0dc577a4dc fix compiler crash regression with explicit destructor calls [backport:2.2] (#25717)
Unfortunately I do not have a test case for this (although I can link
[this package
test](60f1be9037/tests/test_simple_combined.nim)
which broke), but this is a regression caused by #24841 (which was
backported to 2.2.4) that causes the following compiler crash:

```
assertions.nim(34)       raiseAssert
Error: unhandled exception: ccgtypes.nim(230, 13) `false` mapType: tyGenericInvocation [AssertionDefect]
```

Codegen is traversing the type of the symbol of an explicit destructor
call, but the symbol is the uninstantiated generic hook. This happens
because #24841 changed the code which gives explicit destructor calls
the proper attached destructor to use `replaceHookMagic`, which now
skips `abstractVar` from the type to get the destructor whereas
previously it was just `{tyAlias, tyVar}`. This skips `tyGenericInst`
and also `tyDistinct`. I cannot explain why the skipped `tyGenericInst`
does not have the right destructor but it's not really unexpected, and
skipping `tyDistinct` is just wrong.

To fix this, just `{tyAlias, tyVar, tySink}` are skipped.
2026-04-08 00:51:47 +02:00
Andreas Rumpf
6621d64398 fixes #25577 (#25691) 2026-04-07 18:07:34 +02:00
Ryan McConnell
184d423779 fixes 25713; Allow addr of object variant's discriminant under uncheckedAssign (#25714)
#25713

```nim
type
  K = enum
    k1,k2
  Variant = object
    case kind: K
    of k1:
      discard
    of k2:
      discard

proc a(x: var K) = discard
proc b(x: ptr K) = discard

var x = Variant(kind: k1)
{.cast(uncheckedAssign).}:
  # must be within uncheckedAssign to work
  a(x.kind)
# doesn't work out of or under uncheckedAssign
b(addr x.kind)
```
2026-04-07 06:59:24 +02:00
Jake Leahy
f9524861f3 Fix generic tuple unpacking in iterators (#25705)
Fixes #25704 

This makes sure that `iter` still has `tyGenericInst` skipped like
before, without skipping it for `iterType` which requires it
2026-04-05 14:00:04 +02:00