carp-lang / Carp

A statically typed lisp, without a GC, for real-time applications.
Apache License 2.0
5.51k stars 173 forks source link

References must keep track of their origin #470

Open hellerve opened 5 years ago

hellerve commented 5 years ago

Currently, references can be invalidated by invalidating their origin inside their scope.

(defn use-up [x] ())

(defn main []
  (let-do [a [@"hi"]
           n (Array.nth &a 0)]
    (use-up a)
    (println* n))) ; we used a already! this is bad!

It is also possible to set references to point to values in a more short-lived scope:

(defn main []
  (let-do [x ""]
    (let [a [@"hi"]]
      (set! x (Array.nth &a 0)))
    (println* x))) ; a was already dropped!

Both of these can be prevented by checking the origin of a reference and whether the origin scope still exists; an error could be emitted if it doesn’t.

Cheers

eriksvedang commented 4 years ago

The compiler now cathes this error properly.

eriksvedang commented 4 years ago

Or actually only the first one is caught (missed that there were a second one). So this will have to be fixed still...

eriksvedang commented 4 years ago

I think the second one requires the fixes I'm working on in the sets-of-lifetimes branch.

redbar0n commented 3 months ago

maybe data structures like Array should be able to take ownership (or have ownership automatically transferred to it when it has a reference to a variable that goes out of scope and would otherwise be deallocated) ?