-
-
Save skryukov/533de545f37170e05ae739c5a01899de to your computer and use it in GitHub Desktop.
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
class MathParser | |
# Token types from our lexer | |
token tPLUS tMINUS tSTAR | |
tDIVIDE tLPAREN tRPAREN | |
tNUMBER | |
# operator precedence | |
prechigh | |
left tSTAR tDIVIDE | |
left tPLUS tMINUS | |
preclow | |
rule | |
# exp is one of the other rules | |
exp: operation | |
| paren | |
| number | |
# return :number node | |
number: tNUMBER { result = [:number, val[0]] } | |
# return result between parentheses | |
paren: tLPAREN exp tRPAREN { result = val[1] } | |
# return :send node for all operations | |
operation: exp tPLUS exp { result = [:send, val[0], val[1].to_sym, val[2]] } | |
| exp tMINUS exp { result = [:send, val[0], val[1].to_sym, val[2]] } | |
| exp tSTAR exp { result = [:send, val[0], val[1].to_sym, val[2]] } | |
| exp tDIVIDE exp { result = [:send, val[0], val[1].to_sym, val[2]] } | |
end | |
---- header | |
# see https://gist.github.com/skryukov/6568d7baecfe696c02f9dc3cc14240c2 | |
require_relative "./lexer.rb" | |
---- inner | |
def parse(arg) | |
@tokens = Lexer.new.run(arg) | |
do_parse | |
end | |
def next_token | |
@tokens.shift | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment