After a few days around I discover everything I needed existed already built in and I just need to learn about it.
Ripper provides a symbolic expression tree for your code.
As it's in the standard library, you can only start using it.
I love to use
ruby -e to test some code inline. Then, let's start with
something to learn about the lexer:
We can start with a simply tokenize. That will split your code into atoms to compile each piece in the sequence.
$ ruby -r ripper -e 'p Ripper.tokenize("1 + 2")'
The lexer will tag each tokenized piece and identify each part of the statement:
$ ruby -r ripper -e 'p Ripper.sexp("1+2")'
The output should be something like:
Checking one more example:
$ ruby -r ripper -r pp -e 'pp Ripper.lex("def a; end")'
You can also call the
Ripper.sexp to get the symbolic expression of your code:
pp to make it more easy to ready:
$ ruby -r ripper -r pp -e 'pp Ripper.sexp("1+2 + ( 3 * 4)") '
This feature is cool and strange. I can't find a proper documentation, and I debug it by myself trying to understand better the strategy. It's a kind of regular expression mixed with the lexer. Take a look at the example:
It's useful for grep for specific sequence of node types, for example, lets
check for a sequence of
int float float in the operation:
Take a look at the official example, and it's cooler than mine.
That's all for today! Thanks for reading o/