Skip to content

Instantly share code, notes, and snippets.

@skryukov
Created October 23, 2021 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skryukov/533de545f37170e05ae739c5a01899de to your computer and use it in GitHub Desktop.
Save skryukov/533de545f37170e05ae739c5a01899de to your computer and use it in GitHub Desktop.
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