Search code examples
rubyparsingabstract-syntax-trees-expressionruby-ripper

What is the meaning of the 'send' keyword in Ruby's AST?


I am trying to learn the Ruby lexer and parser (whitequark parser) to know more about the procedure to further generate machine code from a Ruby script.

On parsing the following Ruby code string.

def add(a, b)
    return a + b
end

puts add 1, 2

It results in the following S-expression notation.

s(:begin,
    s(:def, :add,
        s(:args,
            s(:arg, :a),
            s(:arg, :b)),
        s(:return,
            s(:send,
                s(:lvar, :a), :+,
                s(:lvar, :b)))),
    s(:send, nil, :puts,
        s(:send, nil, :add,
            s(:int, 1),
            s(:int, 3))))

Can anyone please explain me the definition of the :send keyword in the resultant S-expression notation?


Solution

  • Ruby is built on top of “everything is an object” paradigm. That said, everything, including numbers, is an object.

    Operators, as we see them in plain ruby code, are nothing but a syntactic sugar for respective object’s methods calls:

    3.14.+(42)
    #⇒ 45.14
    

    The above is exactly how Ruby treats 3.14 + 42 short notation. It, in turn, might be written using generic Object#send:

    3.14.send :+, 42
    #⇒ 45.14
    

    The latter should be read as: “send the message :+ with argument[s] (42) to the receiver 3.14.”