Merge: Explain failed asserts for easier debugging, error reporting and TDD
authorJean Privat <jean@pryen.org>
Thu, 1 Mar 2018 14:42:02 +0000 (09:42 -0500)
committerJean Privat <jean@pryen.org>
Thu, 1 Mar 2018 14:42:02 +0000 (09:42 -0500)
commit8c9a94e5577adab5a3c97a68294815b7b36f6c08
treeab4f1cff66873ad52754677dfca1697050fa424c
parentb4e876e28a4622b7bc72eed0f1f9630f576de881
parent4cd1e2f7294dbbcb152468c9c0d0a8972c83583b
Merge: Explain failed asserts for easier debugging, error reporting and TDD

When an assert fails, the program prints the details of the failed expression to the console, above the stacktrace. This change makes it easier and even fun to implement methods by writing the tests first and using nitunit to debug.

The AST rewrite can explain binary comparisons (printing the expected and actual values in a similar way to JUnit's `assertEquals`), `not` and `isa` expressions, as well as the receiver and arguments sent to a method returning `Bool`. It does not explain `and` & `or` expressions as they could cause unwanted side-effects in the current implementation.

Example of a method call:
~~~
var x = 0.0
var y = 1.0
assert x.is_approx(y, 0.5)
~~~

Output:
~~~
Runtime assert: 0.0.is_approx(1.0, 0.5)
Runtime error: Assert failed (a.nit:3)
~~~

Expressions are executed only once by assigning each printed values to a variable. The values are then printed via a superstring, inheriting its automatic call to `to_s`.

Example of a binary comparison with a possible side-effect and protected nullable types:

~~~
fun foo(v: nullable Int): nullable Int do
print "foo"
return v
end

assert foo(null) != null
~~~

Output:

~~~
foo
Runtime assert: null != null
Runtime error: Assert failed (b.nit:6)
~~~

---

I don't like that the phase has so many dependencies, but they appeared to be required by `ASTBuilder` which greatly simplify the code and they also help to deal with nullable types. Future work could probably remove some dependencies and work on the pure AST.

This PR may break the reproducibility of some tests, but I have another PR in the works that could fix that.

Pull-Request: #2541
Reviewed-by: Jean Privat <jean@pryen.org>
Reviewed-by: Lucas Bajolet <r4pass@hotmail.com>