Skip to content

Instantly share code, notes, and snippets.

@vidarh
Created June 8, 2023 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vidarh/485bf16a1224510602cbcffec131c79b to your computer and use it in GitHub Desktop.
Save vidarh/485bf16a1224510602cbcffec131c79b to your computer and use it in GitHub Desktop.
Minimal Ruby S-expression parser w/test case showing using %(string syntax) to naturally embed s-expressions in Ruby code.
require 'strscan'
class Sexp
def initialize(str); @s = StringScanner.new(str); end
def s(e); @s.scan(e); end
def r(e); s(e) or raise "Expected #{x}"; end
def list; s("(")&&b=body and r(")") and b; end
def exp; s(/[a-zA-Z][\w_-]*/)&.to_sym||s(/[0-9]+/)&.to_i||s(/"[^"]*"/)&.[](1..-2)||list||r("exp"); end
def body; r=[]; while s(/\s*/) and !@s.eos? and !@s.check(")") and e=exp; r<<e; end; r; end
end
def sexp str; Sexp.new(str).body; end
p sexp %(
this (is a (test) 42 "some str")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment