nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.62k stars 1.47k forks source link

Compiler Seg faulting when using "object" instead of "ref object" for nested object #15186

Open davidbruce opened 4 years ago

davidbruce commented 4 years ago

Originally from: https://forum.nim-lang.org/t/6679

I ran into a incredible frustrating issue where my compiler was seg faulting due to missing a ref in a type declaration. In the below code just swapping Node[T] = object to Node[T] = ref object stops the seg fault and compiles and runs as expected. In fact on MacOS I don't even get the segfault error, Segmentation fault (core dumped), instead the compiler just mysteriously stopped. The same thing happens with the devel branch I grabbed from choosenim.

type
  Node[T] = object
      item: T
      next: Node[T]
  Bag*[T] = ref object
      first: Node[T]
      size: int

Example

You can reproduce the seg fault here: https://play.nim-lang.org/#ix=2u3O

import random

type
  Node[T] = object
      item: T
      next: Node[T]
  Bag*[T] = ref object
      first: Node[T]
      size: int

func isEmpty*(bag: Bag): bool =
   bag.first == nil

func size*(bag: Bag): int =
   bag.size

func add*[T](bag: Bag[T], item: T): void =
   var oldFirst = bag.first
   bag.first = new(Node[T])
   bag.first.item = item
   bag.first.next = oldFirst
   bag.size += 1

var testBag = new(Bag[int])
for i in 1 .. 10:
  randomize()
  testBag.add(i * rand(100))

echo "Is the bag empty: " & $testBag.isEmpty
echo "Bag size: " & $testBag.size

Current Output

Segmentation fault (core dumped)

Expected Output

An error of some kind pointing out the need for a reference.

Nim Compiler Version 1.0 and beyond

metagn commented 10 months ago

Still an issue, same as #14646.