Created
November 1, 2015 07:55
-
-
Save xhjkl/92d69dde8d8dd074a3fe to your computer and use it in GitHub Desktop.
Punkish symbolic expression parser
This file contains 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
def parse_symbolic(text) | |
# Return nested list of symbols as parsed from input S-expr | |
# | |
# text -- string with an S-expr | |
# | |
lexeme = /(?<quote_run>(?<quote>['"])(?<content>.*)\k<quote>(?<!\\))|(?<whole_word>\w+)|(?<bracket>[()])/ | |
text.strip! | |
text.gsub!(lexeme) { |match| | |
first_nonempty_index = Regexp.last_match.captures.index { |x| not x.nil? } | |
case lexeme.names[first_nonempty_index] | |
when 'quote_run' | |
":#{match[1...-1].inspect}," | |
when 'whole_word' | |
":#{match}," | |
when 'bracket' | |
{'(' => '[', ')' => '],'}[match] | |
end | |
} | |
text.chomp! ',' | |
eval text | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment