Commit Graph

6848 Commits

Author SHA1 Message Date
ringabout
5daa186845 fix #25508; ignores void types in the backends (#25550)
fix #25508

(cherry picked from commit e4b1d8eebc)
2026-03-09 10:47:45 +01:00
metagn
f201c4e225 fix compiler crash with uncheckedAssign and range/distinct discrims [backport] (#25585)
On simple code like:

```nim
type Foo = object
  case x: range[0..7]
  of 0..2:
    a: string
  else:
    b: string

var foo = Foo()
{.cast(uncheckedAssign).}:
  foo.x = 5
```

The compiler tries to generate a destructor for the variant fields by
checking if the discrim is equal to the old one, but the type is not
skipped when looking for an `==` operator in system, so any
discriminator with type `range`/`distinct`/etc crashes with:

```
(10, 9) Error: can't find magic equals operator for type kind tyRange
```

This is fixed by just skipping abstract types.

(cherry picked from commit 7a87e7d199)
2026-03-09 10:13:04 +01:00
ringabout
98c67dff7f fixes #25566; {.align.} pragma where each 16-byte-aligned (#25570)
fixes #25566

(cherry picked from commit 8e2547a5e2)
2026-03-04 09:17:19 +01:00
Ryan McConnell
e4f1ccba8b fixes #25572 ICE evaluating closure iter with object conversion (#25575)
(cherry picked from commit 46cddbccd6)
2026-03-04 09:17:07 +01:00
ringabout
dc8d538683 fixes #25262; proc v[T: typedesc]() = discard / v[0]() compiles even though 0 isn't a typedesc (#25558)
fixes #25262

```nim
if constraint != nil and constraint.kind == tyTypeDesc:
  n[i].typ = e.typ
else:
  n[i].typ = e.typ.skipTypes({tyTypeDesc})
```
at least when `constraint` is a typedesc, it should not skip
`tyTypeDesc`

```nim
if arg.kind != tyTypeDesc:
  arg = makeTypeDesc(m.c, arg)
```
Wrappers literals into typedesc, which can cause problems. Though, it
doesn't seem to be necessary

(cherry picked from commit bd709f9b4c)
2026-03-02 11:01:01 +01:00
ringabout
f7a18fceba fixes #25553; Invalid codegen for accessing tuple in array (#25555)
fixes #25553

(cherry picked from commit 4566ffaca9)
2026-03-02 10:58:24 +01:00
Raka Hourianto
5eb96d40ee nre: fix replacement string parser OOB access, numeric refs, and unterminated named refs (#25560)
1. A trailing `$` at the end of a replacement string could read out of
bounds via `how[i + 1]`; this now raises `ValueError` instead.

2. Numeric capture parsing used `id += (id * 10) + digit` instead of `id
= (id * 10) + digit`, so multi-digit refs were parsed incorrectly (e.g.
`$12` resolved as capture 13 instead of 12).

4. Unterminated named replacement syntax (e.g. `${foo)` is now rejected
with ValueError instead of being accepted and parsed inconsistently.

Found and fixed by GPT 5.3 Codex.

(cherry picked from commit 9b2b286baf)
2026-03-02 10:55:53 +01:00
ringabout
ca9031f7f5 fixes #21281; proc f(x: static[auto]) doesn't treat x as static (#25543)
fixes #21281

(cherry picked from commit 74499e4561)
2026-02-26 18:18:23 +01:00
narimiran
4c15179df7 Revert "fixes #21281; proc f(x: static[auto]) doesn't treat x as static (#25543)"
This reverts commit dc1064da23.
2026-02-26 18:10:29 +01:00
ringabout
a9111b03e5 allows implicitRangeConvs for literals (#25542)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
(cherry picked from commit a3157537e1)
2026-02-26 17:35:22 +01:00
ringabout
dc1064da23 fixes #21281; proc f(x: static[auto]) doesn't treat x as static (#25543)
fixes #21281

(cherry picked from commit 74499e4561)
2026-02-26 17:35:13 +01:00
ringabout
8ccba2dc86 fixes #25509; removes void fields from a named tuple type (#25515)
fixes #25509

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
(cherry picked from commit b51be75613)
2026-02-26 17:34:42 +01:00
ringabout
bc1b7060b5 enable --warning:ImplicitRangeConversion (#25477)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
(cherry picked from commit 1451651fd9)
2026-02-26 17:32:51 +01:00
ringabout
b3ecf7dbef fixes #25338; Switch default mangling back to cpp (#25343)
fixes #25338

(cherry picked from commit ed8e5a7754)
2026-02-26 17:27:01 +01:00
ringabout
5ec6391124 fixes #25005; new doesn't work with ref object (#25532)
fixes #25005

In `semTypeIdent`, when resolving a typedesc parameter inside a generic
instantiation, the code took a shortcut: it returned the symbol of the
element type (`bound = result.typ.elementType.sym`). However, for
generic types like `RpcResponse[T] = ref object`, the instantiated
object type (e.g., `RpcResponse:ObjectType[string]`) is a copy with a
new type ID but still points to the same symbol as the uninstantiated
generic body type. That symbol's .typ refers to the original
uninstantiated type, which still contains unresolved generic params `T`

(cherry picked from commit e58acc2e1e)
2026-02-26 17:25:33 +01:00
Zoom
689111936c Feat: std: parseopt parser modes (#25506)
Adds configurable parser modes to std/parseopt module. **Take two.**

Initially solved the issue of not being able to pass arguments to short
options as you do with most everyday CLI programs, but reading the tests
made me add more features so that some of the behaviour could be changed
and here we are.

**`std/parseopt` now supports three parser modes** via an optional
`mode` parameter in `initOptParser` and `getopt`.

Three modes are provided:
- `NimMode` (default, fully backward compatible),
- `LaxMode` (POSIX-inspired with relaxed short option handling),
- `GnuMode` (stricter GNU-style conventions).

The new modes are marked as experimental in the documentation.

The parser behaviour is controlled by a new `ParserRules` enum, which
provides granular feature flags that modes are built from. This makes it
possible for users with specific requirements to define custom rule sets
by importing private symbols, this is mentioned but clearly marked as
unsupported.

**Backward compatibility:**

The default mode preserves existing behaviour completely, with a single
exception: `allowWhitespaceAfterColon` is deprecated.

Now, `allowWhitespaceAfterColon` doesn't make much sense as a single
tuning knob. The `ParserRule.prSepAllowDelimAfter` controls this now.
As `allowWhitespaceAfterColon` had a default, most calls never mention
it so they will silently migrate to the new `initOptParser` overload. To
cover cases when the proc param was used at call-site, I added an
overload, which modifies the default parser mode to reflect the required
`allowWhitespaceAfterColon` value. Should be all smooth for most users,
except the deprecation warning.

The only thing I think can be classified as the breaking change is a
surprising **bug** of the old parser:

```nim
let p = initOptParser("-n 10 -m20 -k= 30 -40",  shortNoVal =  {'v'})
#                                     ^-disappears
```

This is with the aforementioned `allowWhitespaceAfterColon` being true
by default, of course. In this case the `30` token is skipped
completely. I don't think that's right, so it's fixed.

Things I still don't like about how the old parser and the new default
mode behave:

1. **Parser behaviour is controlled by an emptiness of two containers**.
This is an interesting approach. It's also made more interesting because
the `shortNoVal`/`longNoVal` control both the namesakes, but *and also
how their opposites (value-taking opts) work*.
---

**Edit:**

2. `shortNoVal` is not mandatory:
    ```nim
	let p = initOptParser(@["-a=foo"], shortNoVal = {'a'})
	# Nim, Lax parses as: (cmdShortOption, "a", "foo")
	# GnuMode  parses as: (cmdShortOption, "a", "=foo")
	```
In this case, even though the user specified `a` as no no-val, parser
ignores it, relying only on the syntax to decide the kind of the
argument. This is especially problematic with the modes that don't use
the rule `prShortAllowSep` (GnuMode), in this case the provided input is
twice invalid, regardless of the `shortNoVal`.

With the current parser architecture, parsing it this way **is
inevitable**, though. We don't have any way to signal the error state
detected with the input, so the user is expected to validate the input
for mistakes.
Bundling positional arguments is nonsensical and short option can't use
the separator character, so `[cmd "a", arg "=foo"]` and `[cmd "a", cmd
"=", cmd "f"...]` are both out of the question **and** would complicate
validating, requiring keeping track of a previous argument. Hope I'm
clear enough on the issue.

**Future work:**

1. Looks like the new modes are already usable, but from the discussions
elsewhere it looks like we might want to support special-casing
multi-digit short options (`-XX..`) to allow numerical options greater
than 9. This complicates bundling, though, so requires a bit of thinking
through.

2. Signaling error state?

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
(cherry picked from commit 7c873ca615)
2026-02-20 09:02:26 +01:00
ringabout
34a594abec fixes #25475; incompatible types errors for array types with different index types (#25505)
fixes #25475

```nim
var x: array[0..1, int] = [0, 1]
var y: array[4'u..5'u, int] = [0, 3]

echo x == y
```

sigmatch treats array compatibility by element type + length, not by the
index (range) type. Perhaps backend should do the same check

(cherry picked from commit 97fed258ed)
2026-02-16 09:14:03 +01:00
Yuriy Glukhov
f10dda264c Importc codegen fix (#25511)
This fixes two issues with impotc'ed types.
1. Passing an importc'ed inherited object to where superclass is
expected emitted `v.Sup` previously. Now it emits `v`, similar to cpp
codegen.
2. Casting between different nim types that resolve to the same C type
previously was done like `*(T*)&v`, now it is just `v`.

(cherry picked from commit 937e647f4f)
2026-02-16 09:13:45 +01:00
Andreas Rumpf
c5455c1515 attempt to fix final issue with Nim's multi-threaded allocator (#25513)
(cherry picked from commit b41049988f)
2026-02-16 09:03:24 +01:00
ringabout
334f2d6a87 fixes #25457; make rawAlloc support alignment (#25476)
fixes https://github.com/nim-lang/Nim/issues/25457

Small chunks allocate memory in fixed-size cells. Each cell is
positioned at exact multiples of the cell size from the chunk's data
start, which makes it much harder to support alignment

```nim
sysAssert c.size == size, "rawAlloc 6"
if c.freeList == nil:
  sysAssert(c.acc.int + smallChunkOverhead() + size <= SmallChunkSize,
            "rawAlloc 7")
  result = cast[pointer](cast[int](addr(c.data)) +% c.acc.int)
  inc(c.acc, size)
```

See also https://github.com/nim-lang/Nim/pull/12926

While using big trunk, each allocation gets its own chunk

(cherry picked from commit 94008531c1)
2026-02-13 09:39:30 +01:00
ringabout
29125f0bc7 fixes #25494; [regression] Crash on enum ranges as default parameters in generic procs (#25496)
fixes #25494;

(cherry picked from commit ae5f864bff)
2026-02-10 17:22:52 +01:00
Yuriy Glukhov
2ddeabceaf Fixes #25340 (#25389)
(cherry picked from commit 296b2789b5)
2026-02-10 17:20:32 +01:00
ringabout
9fa69d222f fixes #25482; ICE leaking temporary 3 slotTempInt (#25483)
fixes #25482

(cherry picked from commit a04f720217)
2026-02-10 17:20:21 +01:00
ringabout
d48fc130c1 fixes #24706; Warn on implicit range downsizing (#25451)
fixes #24706

(cherry picked from commit bfc2786718)
2026-02-02 07:59:57 +01:00
Tomohiro
c86e7a0ca9 fixes #25459; hashType returns different hash from instantiated generics with distinct types (#25471)
`hashType` proc returned the same hash value from different instanced
generics types like `D[int64]` and `D[F]`.
That caused the struct type with wrong field types.

object/tuple type size check code is generated when it is compiled with
`-d:checkAbi` option.

(cherry picked from commit 88e7adfcb7)
2026-02-02 07:57:46 +01:00
Gianmarco
d9ed8f2717 Make it so that every feature can be used in panicoverride files (#25300)
Refer to #25298

(cherry picked from commit e7809364b3)
2026-01-26 09:13:58 +01:00
ringabout
35429f6252 fixes #25441; fixes #7355; deletes void args from the argument list (#25455)
fixes #25441; fixes #7355

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit 81610095e6)
2026-01-26 09:13:27 +01:00
ringabout
7277d95b3c fixes #19831; add --styleCheck:warning (#25456)
fixes #19831

(cherry picked from commit f44700e638)
2026-01-26 09:13:17 +01:00
ringabout
ba8ff51f2d fixes #25074; Long integer literal truncated without warning (#25449)
fixes #25074

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
(cherry picked from commit ace09b3cab)
2026-01-26 09:13:06 +01:00
ringabout
a4982bd74d fixes #25446; [FieldDefect] with static: discard cast[pointer](default(pointer)) (#25448)
fixes #25446

supports this since `static: discard cast[pointer](nil)` works

(cherry picked from commit 39864980d1)
2026-01-26 09:12:59 +01:00
ringabout
196f444699 fixes #25400; Naked raised causes wrong exception effect (#25422)
fixes #25400

infers `Exception` for Naked raised

(cherry picked from commit 9a23ff36bd)
2026-01-26 09:12:51 +01:00
ringabout
97c160271c fixes #25419; lift magic types to typeclasses (#25421)
fixes #25419

(cherry picked from commit 40480fe348)
2026-01-15 14:47:22 +01:00
Jake Leahy
c022120ebb Raw switch for jsondoc (#24568)
Implements #21928

Adds a `--raw` (since thats what the original issue used, suggestions
welcome) switch which stops the jsondoc gen from rendering rst/markdown.

Implemented by making `genComment` check if it needs to return the raw
string or not. This required switching the related procs to using
`Option` to handle how `nil` values were returned before. The `nil`
returns were eventually ignored so just ignoring `none(T)` has the same
effect.

Doesn't support `runnableExamples` since jsondocs doesn't support them
either

(cherry picked from commit c1e381ae8d)
2026-01-12 08:51:47 +01:00
Copilot
e45bef46a1 Add test case for jsffi type mismatch error (#16726) (#25429)
Issue #16726 reported an internal compiler error (`semcall.nim(229, 18)
nArg != nil`) when calling `toJs` with invalid arguments. The bug has
been fixed in the current codebase but lacked a regression test.

```nim
import std/jsffi
let a = toJs(3)
let b = a.toJs(int)  # Now produces: Error: type mismatch
                      # Previously: internal error
```

**Changes:**
- Added `tests/js/t16726.nim` to verify proper type mismatch error is
reported instead of internal compiler error

<!-- START COPILOT ORIGINAL PROMPT -->

<details>

<summary>Original prompt</summary>

>
> ----
>
> *This section details on the original issue you should resolve*
>
> <issue_title>internal error: semcall.nim(229, 18) nArg !=
nil</issue_title>
> <issue_description>### Example
> the code below should give a clean CT error, not an internal error
> ```nim
> import std/jsffi
> let a = toJs(3)
> let b = a.toJs(int)
> ```
>
> ### Current Output
> nim r -b:js main
> compiler/semcall.nim(229, 18) `nArg != nil`
>
> ### Expected Output
> proper CT error
>
> ### Additional Information
> 1.5.1 41965880ce
> </issue_description>
>
> <agent_instructions>adds a test case for it and verify it by `./koch
temp js -r test.nim` before committing</agent_instructions>
>
> ## Comments on the Issue (you are @copilot in this section)
>
> <comments>
> <comment_new><author>@ringabout</author><body>
> related:
https://github.com/nim-lang/Nim/issues/15607</body></comment_new>
> </comments>
>

</details>

<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes nim-lang/Nim#16726

<!-- START COPILOT CODING AGENT TIPS -->
---

💬 We'd love your input! Share your thoughts on Copilot coding agent in
our [2 minute survey](https://gh.io/copilot-coding-agent-survey).

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
(cherry picked from commit 83d7d8c634)
2026-01-12 08:49:58 +01:00
ringabout
a21a1c99cd fixes #19983; implements bitmasked bitshifting for all backends (#25390)
replaces https://github.com/nim-lang/Nim/pull/11555

fixes https://github.com/nim-lang/Nim/issues/19983
fixes https://github.com/nim-lang/Nim/issues/13566

- [x] JS backend

---------

Co-authored-by: Arne Döring <arne.doering@gmx.net>
(cherry picked from commit f1b97caf92)
2026-01-12 08:48:55 +01:00
ringabout
f3f76cdc52 closes #23394; adds a test case (#25416)
closes #23394

(cherry picked from commit 89c8f0aa49)
2026-01-09 09:14:09 +01:00
Esteban C Borsani
0ae9f5e4df Add parseEnum support for triple quoted string and raw string enum values (#25401)
(cherry picked from commit ae8a1739f8)
2026-01-09 09:08:34 +01:00
Jake Leahy
34e61d5ae6 Fix tupleLen not skipping aliases (#25392)
This code was failing to compile with `Error: unhandled exception:
semmagic.nim(247, 5) operand.kind == tyTuple tyAlias [AssertionDefect]`
```nim
import std/typetraits

type
  Bar[T] = T
  Foo = Bar[tuple[a: int]]

echo Foo.tupleLen
```

Fix was just making `tupleLen` skip alias types also

(cherry picked from commit 91d51923b9)
2026-01-09 08:49:48 +01:00
bptato
1dafcbd2a7 Fix std/hashes completely ignoring endianness (#25386)
This is a problem on big-endian CPUs because you end up with nimvm
computing something different than Nim proper, so e.g. a const table
won't work.

I also took the liberty to replace a redundant implementation of load4
in murmurHash.

(Thanks to barracuda156 for helping debug this.)

(cherry picked from commit a061f026a8)
2026-01-09 08:49:09 +01:00
ringabout
57e4b364d2 fixes #25387; embedsrc breaks with Line Continuation (#25388)
fixes #25387

https://stackoverflow.com/questions/30286253/how-to-escape-backslash-in-comment

- adding a whitespace or `\t` after `\` breaks the `goto` block
- `\* *\` doesn't support nesting, causing problems for using it in the
Nim comments

(cherry picked from commit a41bbf6901)
2026-01-09 08:49:03 +01:00
ringabout
6d32ceaebb fixes #25254; fixes #10395; Invalid pred in when swallowed (#25385)
fixes #25254
fixes #10395

(cherry picked from commit 5e53a70e62)
2026-01-09 08:48:56 +01:00
elijahr
f4fd26d403 Fix sizeof(T) in typedesc templates called from generic type when clauses (#25374)
The `hasValuelessStatics` function in `semtypinst.nim` only checked for
`tyStatic`, missing `tyTypeDesc(tyGenericParam)`. This caused
`sizeof(T)` inside a typedesc template called from a generic type's
`when` clause to error with "'sizeof' requires '.importc' types to be
'.completeStruct'".

The fix adds a check for `tyTypeDesc` wrapping `tyGenericParam`,
recognizing it as an unresolved generic parameter that needs resolution
before evaluation.

Also documents the `completeStruct` pragma in the manual.

(cherry picked from commit b819472e74)
2026-01-09 08:48:29 +01:00
elijahr
75f818f385 fix #17630: Implement cycle detection for recursive concepts (#25353)
fixes #17630

## Recursive Concept Cycle Detection

- Track (conceptId, typeId) pairs during matching to detect cycles
- Changed marker from IntSet to HashSet[ConceptTypePair]
- Removed unused depthCount field
- Added recursive concepts documentation to manual
- Added tests for recursive concepts, distinct chains, and co-dependent
concepts

## Fix Flaky `tasyncclosestall` Test

The macOS ARM64 CI jobs were failing due to a flaky async socket test
(unrelated to concepts).

The test only accepted `EBADF` as a valid error code when closing a
socket with pending writes. However, depending on timing, the kernel may
report `ECONNRESET` or `EPIPE` instead:

- **EBADF**: Socket was closed locally before kernel detected remote
state
- **ECONNRESET**: Remote peer sent RST packet (detected first)
- **EPIPE**: Socket is no longer connected (broken pipe)

All three are valid disconnection errors. The fix accepts any of them,
making the test reliable across platforms.

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
(cherry picked from commit 1324183c38)
2026-01-09 08:47:57 +01:00
ringabout
919d0d5ea8 fixes #25369 (#25370)
fixes #25369

(cherry picked from commit 548b1c6ef8)
2025-12-18 20:53:04 +01:00
Andreas Rumpf
90b7517656 refs https://github.com/nim-lang/Nim/pull/25353 make tasyncclosestall… (#25366)
….nim less flaky

(cherry picked from commit 334ac3f588)
2025-12-18 20:52:17 +01:00
metagn
c8556ef5df consider generic param type as typedesc in tuple type expressions (#25316)
fixes #25312

Tuple expressions `(a, b, c)` can be either types or values depending on
if their elements are typedescs or values, this is checked by checking
if the type of the element is `tyTypeDesc`. However when an
`skGenericParam` symbol is semchecked by `semSym` it is given its own
`tyGenericParam` type rather than a `tyTypeDesc` type, this seems to be
necessary for signatures to allow wildcard generic params passed to
static constrained generic params (tested in #25315). The reason
`semSym` is called is that `semGeneric` for generic invocations calls
`matches` which sems its arguments like normal expressions.

To deal with this, an expression of type `tyGenericParam` and with a
`skGenericParam` sym is allowed as a type in the tuple expression. A
problem is that this might consider a value with a wildcard generic
param type as a type. But this is a very niche problem, and I'm not sure
how to check for this. `skGenericParam` symbols stay as idents when
semchecked so it can't be checked that the node is an `skGenericParam`
symbol. It could be checked that it's an ident but I don't know how
robust this is. And maybe there is another way to refer to a wildcard
generic param type instead of just its symbol, i.e. another kind of
node.

This also makes #5647 finally work but a test case for that can be added
after.

(cherry picked from commit 44d2472b08)
2025-12-10 10:31:59 +01:00
ringabout
6c8ab9f898 fixes #25329; Wrong type for second parameter of procedures "inc", "dec", "succ" and "pred" (#25337)
fixes #25329

(cherry picked from commit e1f2329e55)
2025-12-10 10:31:42 +01:00
elijahr
547416b806 Fixes #25341; Invalid C code for lifecycle hooks for distinct types based on generics (#25342)
(cherry picked from commit 099ee1ce4a)
2025-12-10 10:29:15 +01:00
Yuriy Glukhov
97c41c0f15 Fixes #25330 (#25336)
Fixed state optimizer. It did not replace deleted states in
`excLandingState`.

(cherry picked from commit 8f8814b495)
2025-12-05 15:29:45 +01:00
Ryan McConnell
90efe870c8 concept patch: inheritance (#25317)
adds some inheritance support

---------

Co-authored-by: Andreas Rumpf <araq4k@proton.me>
(cherry picked from commit 86bbc73b3a)
2025-12-05 15:29:15 +01:00