Seite 1 von 1

Reference Counting: Deref of the condition value in If0 evaluation

Verfasst: 6. Mär 2020 15:00
von johanneslauinger
Hi,

I know it's pretty late but maybe someone still has an idea and finds the time to answer. Looking through the implementation for the interpreter with reference counting [0], I asked myself why the If0 branch dereferences the condition/test value (testLoc) *after* evaluating the respective then/else expression:

Code: Alles auswählen

01: case If0(testExpr, thenExpr, elseExpr) =>
02:      val (testLoc, s1) = interp(testExpr, stack, store)
03:      val (loc, s2) = s1.lookup(testLoc) match {
04:           case NumV(0) => interp(thenExpr, stack, s1)
05:           case NumV(_) => interp(elseExpr, stack, s1)
06:           case x => sys.error("can only test numbers, but got: " + x)
07:      }
08:      (loc, s2.deref(testLoc))
("local" line numbers added)

The result from the interp call for thenExpr/elseExpr, which of course if also the result of the match expression in line 3, gets assigned to the (loc, s2) tuple, and then in the resulting store testLoc is freed in line 8.

I couldn't find a reason why it's necessary to dereference testLoc *after* evaluating the then/else branch. Since the testLoc is not passed into the inner interp calls, there is no way thenExpr or elseExpr could use the value, therefore I believe it could be dereferenced before interpreting them, like this:

Code: Alles auswählen

01: case If0(testExpr, thenExpr, elseExpr) =>
02:      val (testLoc, s1) = interp(testExpr, stack, store)
03:      s1.lookup(testLoc) match {
04:           case NumV(0) => interp(thenExpr, stack, s1.deref(testLoc))
05:           case NumV(_) => interp(elseExpr, stack, s1.deref(testLoc))
06:           case x => sys.error("can only test numbers, but got: " + x)
07:      }
Here, I removed line 8 and the value assignment in line 3, making the If0 case return directly the result of the inner match in line 3. I added the deref calls to s1 in lines 4 and 5, therefore the inner interp calls receive a store where testLoc is already freed.

This even gives the inner interp call the ability to use one memory cell more.

Was the original version's purpose solely to avoid the little code duplication of writing "deref(testLoc)" twice? Or am I missing something else here?

Thanks and all the best
Johannes

[0]: https://repository.st.informatik.tu-dar ... ount.scala

Re: Reference Counting: Deref of the condition value in If0 evaluation

Verfasst: 6. Mär 2020 16:33
von mirko-koehler
I think your solution is correct. The value returned from the condition can be dereferenced directly after the interpretation of the condition as nothing can be done with it anymore (i.e. there is no way to get the result from the interpretation of the condition).

Re: Reference Counting: Deref of the condition value in If0 evaluation

Verfasst: 8. Mär 2020 18:13
von johanneslauinger
I see, thank you!