Created
June 8, 2023 15:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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