Commit Graph

23001 Commits

Author SHA1 Message Date
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
dxxb
0028ea563c Fix inconsistent env type with nested procs in iterators (#21242) (#25699)
Nested transformBody/liftLambdas passes used a fresh DetectionPass, so
getEnvTypeForOwner could allocate a duplicate PType for the same owner
while :envP already referenced the inner pass type. When addClosureParam
saw cp.typ != t, it errored.

If both types are env objects for the same routine owner, reuse cp.typ
and sync ownerToType.

Adds regression test tests/iter/t21242_nested_closure_in_iter.nim.
2026-04-04 19:47:01 +02:00
ringabout
854c1f15ba fixes #25687; optimizes seq assignment for orc (#25689)
fixes #25687

This pull request introduces an optimization for sequence (`seq`)
assignments and copies in the Nim compiler, enabling bulk memory copying
for sequences whose element types are trivially copyable (i.e., no GC
references or destructors). This can significantly improve performance
for such types by avoiding per-element loops.

Key changes:

### Compiler code generation improvements

* Added the `elemSupportsCopyMem` function in
`compiler/liftdestructors.nim` to detect if a sequence's element type is
trivially copyable (no GC refs, no destructors).
* Updated the `fillSeqOp` procedure to use a new `genBulkCopySeq` code
path for eligible element types, generating a call to
`nimCopySeqPayload` for efficient bulk copying. Fallback to the
element-wise loop remains for non-trivial types.
[[1]](diffhunk://#diff-456118dde9a4e21f1b351fd72504d62fc16e9c30354dbb9a3efcb95a29067863R665-R670)
[[2]](diffhunk://#diff-456118dde9a4e21f1b351fd72504d62fc16e9c30354dbb9a3efcb95a29067863R623-R655)

### Runtime support

* Introduced the `nimCopySeqPayload` procedure in
`lib/system/seqs_v2.nim`, which performs the actual bulk memory copy of
sequence data using `copyMem`. This is only used for types that are safe
for such an operation.

These changes collectively improve the efficiency of sequence operations
for simple types, while maintaining correctness for complex types.


### Benchmarked the original micro-benchmark:
refc: 3.52s user 0.02s system 99% cpu 3.538 total
orc (after change): 3.46s user 0.01s system 99% cpu 3.476 total

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-02 11:46:49 +02:00
Andreas Rumpf
d389d4fb2f SSO for strings (#25593) 2026-04-02 07:19:43 +02:00
Zoom
be29bcd402 Fix iterable resolution, prefer iterator overloads (#25679)
This fixes type resolution for `iterable[T]`.

I want to proceed with RFC
[#562](https://github.com/nim-lang/RFCs/issues/562) and this is the main
blocker for composability.

Fixes #22098 and, arguably, #19206

```nim
import std/strutils

template collect[T](it: iterable[T]): seq[T] =
  block:
    var res: seq[T] = @[]
    for x in it:
      res.add x
    res

const text = "a b c d"

let words = text.split.collect()
doAssert words == @[ "a", "b", "c", "d" ]
```

In cases like `strutils.split`, where both proc and iterator overload
exists, the compiler resolves to the `func` overload causing a type
mismatch.

The old mode resolved `text.split` to `seq[string]` before the
surrounding `iterable[T]` requirement was applied, so the argument no
longer matched this template.

It should be noted that, compared to older sequtils templates,
composable chains based on `iterable[T]` require an iterator-producing
expression, e.g. `"foo".items.iterableTmpl()` rather than just
`"foo".iterableTmpl()`. This is actually desirable: it keeps the
iteration boundary explicit and makes iterable-driven templates
intentionally not directly interchangeable with older
untyped/loosely-typed templates like those in `sequtils`, whose internal
iterator setup we have zero control over (e.g. hard-coding adapters like
`items`).

Also, I noticed in `semstmts` that anonymous iterators are always
`closure`, which is not that surprising if you think about it, but still
I added a paragraph to the manual.

Regarding implementation:

From what I gathered, the root cause is that `semOpAux` eagerly
pre-types all arguments with plain flags before overload resolution
begins, so by the time `prepareOperand` processes `split` against the
`iterable[T]`, the wrong overload has already won.

The fix touches a few places:

- `prepareOperand` in `sigmatch.nim`:
When `formal.kind == tyIterable` and the argument was already typed as
something else, it's re-semchecked with the
`efPreferIteratorForIterable` flag. The recheck is limited to direct
calls (`a[0].kind in {nkIdent, nkAccQuoted, nkSym, nkOpenSym}`) to avoid
recursing through `semIndirectOp`/`semOpAux` again.

- `iteratorPreference` field `TCandidate`, checked before
`genericMatches` in `cmpCandidates`, gives the iterator overload a win
without touching the existing iterator heuristic used by `for` loops.

**Limitations:**

The implementation is still flag-driven rather than purely
formal-driven, so the behaviour is a bit too broad `efWantIterable` can
cause iterator results to be wrapped as `tyIterable` in
iterable-admitting contexts, not only when `iterable[T]` match is being
processed.

`iterable[T]` still does not accept closure iterator values such
as`iterator(): T {.closure.}`. It only matches the compiler's internal
`tyIterable`, not arbitrary iterator-typed values.

The existing iterator-preference heuristic is still in place, because
when I tried to remove it, some loosely-related regressions happened. In
particular, ordinary iterator-admitting contexts and iterator chains
still rely on early iterator preference during semchecking, before the
compiler has enough surrounding context to distinguish between
value/iterator producing overloads. Full heuristic removal would require
a broader refactor of dot-chain/intermediate-expression semchecking,
which is just too much for me ATM. This PR narrows only the
tyIterable-specific cases.

**Future work:**

Rework overload resolution to preserve additional information of
matching iterator overloads for calls up to the point where the
iterator-requiring context is established, to avoid re-sem in
`prepareOperand`.

Currently there's no good channel to store that information. Nodes can
get rewritten, TCandidate doesn't live long enough, storing in Context
or some side-table raises the question how to properly key that info.
2026-04-01 21:01:55 +02:00
ringabout
9c07bb94c1 fixes #25682; fix vm genAsgn to handle statementListExpr (#25686)
fixes #25682

This pull request introduces a fix to the Nim compiler's assignment code
generation logic to better handle statement list expressions, and adds
regression tests to ensure correct behavior when assigning to object
fields via templates. The changes address a specific bug (#25682)
related to assignments using templates with side effects in static
contexts.

**Compiler code generation improvements:**

* Updated the `genAsgn` procedure in `compiler/vmgen.nim` to properly
handle assignments where the left-hand side is a `nkStmtListExpr`
(statement list expression), ensuring all statements except the last are
executed before the assignment occurs.

**Regression tests for assignment semantics:**

* Added new test blocks in `tests/vm/tvmmisc.nim` to verify that
template-based assignments to object fields work as expected in static
contexts, specifically testing for bug #25682.
2026-04-01 00:24:06 +02:00
ringabout
fb31e86537 fixes #25632; errors incompatibility between {.error.} and {.exportc} pragmas in semProcAux (#25639)
fixes #25632
fixes #25631
fixes #25630

This pull request introduces a compatibility check between the
`{.error.}` and `{.exportc.}` pragmas in procedure declarations.
Specifically, it prevents a procedure from being marked with both
pragmas at the same time, as this combination is now considered invalid.

Pragma compatibility enforcement:

* Added a check in `semProcAux` (in `compiler/semstmts.nim`) to emit a
local error if a procedure is declared with both `{.error.}` and
`{.exportc.}` pragmas, preventing their incompatible usage.
2026-03-31 23:32:24 +02:00
Jacek Sieka
e53058dee0 windows: prefer 64-bit time_t (#25666)
time_t should be a 64-bit type on all relevant windows CRT versions
including mingw-w64 - MSDN recommends against using the 32-bit version
which only is happens when `_USE_32BIT_TIME_T` is explicitly defined -
instead of guessing (and guessing wrong, as happens with recent mingw
versions), we can simply use the 64-bit version always.
2026-03-31 09:52:11 +02:00
ringabout
8076fb40b8 fixes transf cannot handle bare sym for nim ic (#25664)
```nim
template compute(body: untyped): int =
  block:
    body
let x = compute:
  var sum = 0
  for i in 1..10: sum += i
  sum
echo x
```

supersedes https://github.com/nim-lang/Nim/pull/25653

which in
02893e2f4c

```nim
of nkSym:
    genSingleVar(p, it.sym, newSymNode(it.sym), it.sym.astdef)
```

A new branch for `nkSym` is added, though more changes might be needed
if `nkSym` is handled specifically
2026-03-31 09:49:55 +02:00
ringabout
7a82c5920c fixes #25677; fixes #25678; typeAllowedAux to improve flag handling (#25684)
fixes #25677;
fixes #25678

This pull request introduces both a bug fix to the type checking logic
in the compiler and new test cases for lent types involving procedures
and tables. The most significant change is a refinement in how type
flags are handled for procedure and function types in the compiler,
which improves correctness in type allowance checks. Additionally, the
test suite is expanded to cover more complex scenarios with lent types
and table lookups.

**Compiler improvements:**

* Refined the handling of type flags in `typeAllowedAux` for procedure
and function types by introducing `innerFlags`, which removes certain
flags (`taObjField`, `taTupField`, `taIsOpenArray`) before recursing
into parameter and return types. This ensures more accurate type
checking and prevents inappropriate flag propagation.

**Testing enhancements:**

* Added new test blocks in `tests/lent/tlents.nim` to cover lent
procedure types stored in objects and used as table values, including a
function that retrieves such procedures from a table by key.
* Introduced a test case for an object containing a lent procedure
field, ensuring correct behavior when accessing and using these fields.
2026-03-30 15:09:11 +02:00
cui
78282b241f fixes #25674; parsecfg: bound-check CR/LF pair in replace() (#25675)
Fixes bug #25674.

`replace` read `s[i+1]` for a CRLF pair without ensuring `i+1 <
s.len()`, so a value ending in a lone `\\c` (quoted in `writeConfig`)
raised `IndexDefect`.

- Fix: only treat `\\c\\l` when the following character exists.
- Test: `tests/stdlib/tparsecfg.nim` block bug #25674 — fails before
fix, passes after.
2026-03-28 16:22:54 +08:00
cui
5c86c1eda9 fixes #25670; docgen: cmpDecimalsIgnoreCase max() used wrong index for b (#25669)
Fixes bug #25670.

The second argument to `max` in `cmpDecimalsIgnoreCase` used `limitB -
iA` instead of `limitB - iB`, which could mis-order numeric segments
when sorting doc index entries.
2026-03-27 10:20:10 +01:00
cui
7f6b76b34c fixes #25671; commands: fix --maxLoopIterationsVM positive check (#25672)
Fixes bug #25671.

The previous condition `not value > 0` was parsed as `(not value) > 0`,
not `not (value > 0)`, so the check did not reliably enforce a positive
`--maxLoopIterationsvm` limit. Align with `--maxcalldepthvm` by using
`value <= 0`.
2026-03-27 10:19:35 +01:00
ringabout
2fc9c8084c fixes #25658; two overflowed *= causes program deadloop sysFatal on --exceptions:goto (#25660)
fixes #25658
2026-03-27 09:00:14 +08:00
ringabout
e25820cf52 fixes #25642; Add support for static type in semTypeNode (#25646)
fixes #25642
2026-03-26 20:38:54 +01:00
Tomohiro
158d59ce48 fixes #25635; registers module suffix correctly (#25645)
`toNifFilename` proc doesn't return correct Nif file path because module
suffix is registered with wrong proc.
So `moduleFromNifFile` doesn't load the Nif file.
2026-03-24 21:34:46 +08:00
metagn
6f85d348f4 fix @ for openarray on nimscript [backport:2.2] (#25641)
Even on nimscript, the `else` branch of the `when nimvm` below compiles
and gives an "undeclared identifier: copyMem" error. Regression since
#25064.
2026-03-24 08:27:28 +01:00
ringabout
c48f487780 fixes: replace ensureMutable with backendEnsureMutable in ccgtypes (#25640) 2026-03-24 11:49:06 +08:00