Skip to content

Instantly share code, notes, and snippets.

@xhjkl
Created November 1, 2015 07:55
Show Gist options
  • Save xhjkl/92d69dde8d8dd074a3fe to your computer and use it in GitHub Desktop.
Save xhjkl/92d69dde8d8dd074a3fe to your computer and use it in GitHub Desktop.
Punkish symbolic expression parser
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