Date: Wed, 26 Aug 2020 10:49:28 +0000
> Instead of modifying the variant inside of the visitor, could you have the
> visitor return a signal that the variant should be modified?
>
> Another possibility would be to write a pure endomorphism
> from AST nodes to AST nodes. Instead of modifying the node, return a
> new one. Then at the top-level call site, assign the node to the newly returned one.
These two suggestions are plausible workarounds in some cases. However, they come at a price - e.g. the former one defers work that could be done inside the visitor back to the caller - and there can be many calling sites (e.g. a recursive visitor for AST with many node types). The latter is indeed a common technique in functional programming, but it means copying the whole AST even if a small local modification would be sufficient (or one would try re-using parts of the tree, but it's not easy if the visitor can modify the content of nodes, e.g. one would need to implement COW).
Anyway, this is not the point - I agree there are multiple workarounds for this problem, but this can be said about most features of the standard library. One should compare these workarounds with the proposed solution: The sheer convenience of going from an alternative to the enclosing variant at 0-cost is difficult to beat, and (imho) justifies the risk of UB (that can be mitigated as discussed in this thread).
> visitor return a signal that the variant should be modified?
>
> Another possibility would be to write a pure endomorphism
> from AST nodes to AST nodes. Instead of modifying the node, return a
> new one. Then at the top-level call site, assign the node to the newly returned one.
These two suggestions are plausible workarounds in some cases. However, they come at a price - e.g. the former one defers work that could be done inside the visitor back to the caller - and there can be many calling sites (e.g. a recursive visitor for AST with many node types). The latter is indeed a common technique in functional programming, but it means copying the whole AST even if a small local modification would be sufficient (or one would try re-using parts of the tree, but it's not easy if the visitor can modify the content of nodes, e.g. one would need to implement COW).
Anyway, this is not the point - I agree there are multiple workarounds for this problem, but this can be said about most features of the standard library. One should compare these workarounds with the proposed solution: The sheer convenience of going from an alternative to the enclosing variant at 0-cost is difficult to beat, and (imho) justifies the risk of UB (that can be mitigated as discussed in this thread).
Received on 2020-08-26 05:52:59