The structure of s-expressions

Ruby s-expressions are data representing code. In this post you will see the structure of s-expressions for language features supported by Ruby interpreters and the InfraRuby statically typed Ruby compiler.

An s-expression is an object with a type (a Symbol) and optional arguments. The arguments may be s-expressions or other objects. For example, consider this code to call the puts method:

puts "hello, world"

That code can be generated by the meta-ruby gem with this s-expression:

s(:call, nil, "puts", s(:lit, "hello, world"))

That s-expression has type :call and has three arguments: nil, "puts" and another s-expression with type :lit and argument "hello, world".

All examples in this post will follow this format: source code first and then an s-expression to generate that source code.