Rewriting Pharo code

Rewriting code is a powerful tool through which we can reshape the code at scale. This is possible through the very engine that powers refactorings.

Rewriting by example

Rewriting is facilitated by a dedicated snippet in Lepiter. Let's consider this method: GtPrefixTree>>#childrenDo: childrenDo: aBlock children isNil ifTrue: [ ^ self ]. children do: aBlock

Let’s take a look at a rewrite the condition by directly using ifNil:

children isNil ifTrue: [ ^ self ].
  
children ifNil: [ ^ self ].
  

One thing we can notice is that the search was not textual, given that our search does not preserve the same spacing. Indeed, the search happens at the abstract syntax tree level. And of course, we can generalize it, too.

For example, if we want to replace all code regardless of the conditions and the blocks, we can write like this:

``@boolean isNil ifTrue: ``@block
  
``@boolean ifNil: ``@block
  

This gives us much more results that can be applied in bulk to the right.