commit 4f7bbe812987b8ce63143a6fe3bcc82e152d7ef4 Author: vonhyou Date: Mon Apr 12 11:31:07 2021 +0800 finish parsing diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..723ef36 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/minlisp.rb b/minlisp.rb new file mode 100644 index 0000000..f7aa315 --- /dev/null +++ b/minlisp.rb @@ -0,0 +1,38 @@ +# It's a minimal lisp interpreter written in Ruby-lang +# Author: @vonhyou +# Start at: Apr. 10, 2021 + +def tokenize(program) + # Convert scripts to token lists + replacements = { '(' => ' ( ', ')' => ' ) ' } + program.gsub(Regexp.union(replacements.keys), replacements) + .split(' ') +end + +def read_tokens(tokens) + # read expressions from token + raise SyntaxError, 'Unexpected EOF' if tokens.empty? + + token = tokens.shift + if token == '(' + lst = [] + lst << read_tokens(tokens) while tokens[0] != ')' + tokens.shift + return lst + elsif token == ')' + raise SyntaxError, "Unexpected ')'" + else + return atom token + end +end + +def isInteger?(atom) = atom.match?(/^-?\d+$/) +def isFloat?(atom) = atom.match?(/^(-?\d+)(\.\d+)?$/) + +def atom(token) + # Analyse numbers and symbols + return Integer token if isInteger? token + return Float token if isFloat? token + token +end +