From: Jean Privat Date: Thu, 9 Apr 2015 05:24:37 +0000 (+0700) Subject: Merge: new `with` statement X-Git-Tag: v0.7.4~35 X-Git-Url: http://nitlanguage.org Merge: new `with` statement Introduce the `with` statement that is analogous to the `with` of Python or the `uning` of C#. ~~~nit with x = something do x.work end ~~~ That is equivalent with ~~~nit do var x = something x.start x.work x.finish end ~~~ Note that an alternative syntax, without the local variable exists: ~~~nit with something do work end ~~~ that is used when we want some automatic control or whatever. Eg resource allocation or critical section. ~~~nit do var tmp = something tmp.start work tmp.stop end ~~~ Most real-world examples could be ~~~nit with file = path.create do file.write("Bla") end ~~~ and ~~~nit with a_mutex do work end ~~~ ## Names I reused the `finish` method from Iterator. I introduced the antonym `start` for the other side. Note that the `start` is important because it helps the object to know it has to prepare itself for a `finish`. I did not introduce an interface, mainly because I have no idea for a name. C# names it `IDisposable` and the `finish` method is called `Dispose`. There is no `start` because C# designers are lunatic sometime. In python there is no interface (obviously) and the method are called `__enter__` and `__exit__` because Python likes identifiers that resemble words eaten by boas. Note that the returned variable is not the original expression but the result of `__enter__`. With the Python semantic, but the Nit syntax, the first example will be equivalent to ~~~nit do var tmp = something var x = tmp.start x.work x.finish end ~~~ I am not sure of the benefits of the additional complexity, but the the more I thing about it the more I think this could be useful, ex for the control case the `start` can return the handler to `finish`. The issue is that proposed syntax: `with x = something` does not make sense (because `tmp=something` and `x=tmp.start`) thus should be replaced with something else; Python uses `with something as x:` that we can reuse but I do not want because it is ugly. An other alternative I tough of was to reuse the `for` keyword. but It is convoluted. The two previous real world examples will then be ~~~nit for file = path.create do file.write("Bla") end ~~~ and ~~~nit for a_mutex do work end ~~~ Pull-Request: #1243 Reviewed-by: Alexis Laferrière Reviewed-by: Etienne M. Gagnon Reviewed-by: Lucas Bajolet --- 90df56f73c160350d61a2a641271c6dca5904fb0