[swift-evolution] [Review] SE-0007 Remove C-style for-loops with conditions and incrementers

Michel Fortin michel.fortin at michelf.ca
Thu Dec 10 16:31:08 CST 2015


Le 10 déc. 2015 à 16:35, Brent Royal-Gordon <brent at architechies.com> a écrit :

>> In this particular case you can and it won't have any noticeable side effects. But in the general case it has a different behaviour: the increment part is called on break or throw
> 
> I know there’s no single replacement that compactly implements the exact behavior of a `for` loop using a `while` loop. But we don’t usually have to mimic the full behavior:
> 
> * The vast majority of for loops don’t use an iteration variable which shadows something in the enclosing scope, so the fact that the variable isn’t scoped to the loop doesn’t usually matter.

Note that this is actually true *because* the variable is scoped. It's very common to have two loops in a row using the same variable name. This could of course be detected somehow by the migration tool, which could do a reasonably intelligent job here. I'm not that much concerned about this, it's just a minor nuisance.


> * The vast majority of for loops don’t have iteration statements which cause side effects beyond the statement itself, so the fact that `defer` will run an extra time if you exit the loop with `break` or `throw` doesn’t usually matter.

If you discount potential integer overflows, you're right that increments generally won't have side effects.


> If we provide a fix-it, we should try to make sure it doesn’t write broken code. But if that means that, sometimes, we throw up our hands and don’t offer an automatic translation, I don’t think that’s the end of the world. 

So, how do you propose the fix-it tool determines which code has side effects and which code doesn't? I don't think it can. It certainly could recognize some common safe patterns and offer tailored solutions to these patterns however, if you invest enough time in the tool.

There is never a reason for the fix-it tool to abort and not offer a translation. There is a simple solution that will work in all cases, which I presented in my review. It's ugly and verbose. But it's better to have ugly code that is guarantied to works than leaving the code in an uncompilable state.


-- 
Michel Fortin
michel.fortin at michelf.ca
https://michelf.ca



More information about the swift-evolution mailing list